converting byte to string..
-
Tuesday, May 01, 2007 9:33 AM
Hi Experts,
I am new to this platform. I am reading a file(XML) like this:
private
void readfile(string filename, ref byte[] bytes)System.IO.FileStream stream = null;
try
{
stream = new System.IO.FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
if (null != stream)
{
bytes = new byte[stream.Length];
int bytesRead = stream.Read(bytes, 0, (int)stream.Length);
}
}
finally
{
if (null != stream)
{
stream.Close();
}
}
but after this i have to parse the XML file which i am reading, so i have to convert the file data (byte[] bytes in this case) as string, how can i convert byte [] to string because my parser needs "string" not "byte[]" ? The way i am reading file is correct or not ? And if correct then how can i get the data in string format after reading the file, is there any other way ?
Thanks & Regards
Amit
All Replies
-
Tuesday, May 01, 2007 2:23 PM
Encoding ascii = Encoding.ASCII;
char[] asciiChars = new char[ascii.GetCharCount(bytes, 0, bytes.Length)]; ascii.GetChars(bytes, 0, bytes.Length, asciiChars, 0); string asciiString = new string(asciiChars); -
Tuesday, May 01, 2007 3:51 PM
The other (probably easier) way would be to just use a StreamReader instead of a plain stream. You can construct a StreamReader using a filename, and then use the ReadToEnd() method, which reads to the end of the stream and returns a string.
HTH,
--Jeff
-
Tuesday, May 01, 2007 3:54 PMModerator
You’re using rich .NET framework, not standard C libraries. You don’t need to do low level stuff like this, there are classes designed to read text files in any encodings, e.g. StreamReader class.
If you’re reading XML you probably should use even higher level XmlTextReader class which would do XML parsing for you and represent XML as stream of XML elements.
-
Tuesday, May 01, 2007 5:33 PM
Ilya Tumanov wrote: You’re using rich .NET framework, not standard C libraries. You don’t need to do low level stuff like this, there are classes designed to read text files in any encodings, e.g. StreamReader class.
but ... but ... but then you're taking all the fun out of it.
-
Wednesday, May 02, 2007 7:27 AM
jeff_msft wrote: The other (probably easier) way would be to just use a StreamReader instead of a plain stream. You can construct a StreamReader using a filename, and then use the ReadToEnd() method, which reads to the end of the stream and returns a string.
HTH,
--Jeff
Thanks jeff i tried your way and it worked, Thanks to all for supporting me.
Regards
Amit

