I received the contents of a text file returned in binary values:
Byte[] buf = new Byte[size];
stream = File.InputStream;
stream.Read(buf, 0, size);
How can I convert this to ASCII?
You can use:
System.Text.Encoding.ASCII.GetString(buf);
But sometimes you will get a weird number instead of the string you want. In that case, your original string may have some hexadecimal character when you see it. If it's the case, you may want to try this:
System.Text.Encoding.UTF8.GetString(buf);
Or as a last resort:
System.Text.Encoding.Default.GetString(bytearray);
Encoding.ASCII.GetString(buf);
As an alternative to reading a data from a stream to a byte array, you could let the framework handle everything and just use a StreamReader
set up with an ASCII encoding to read in the string. That way you don't need to worry about getting the appropriate buffer size or larger data sizes.
using (var reader = new StreamReader(stream, Encoding.ASCII))
{
string theString = reader.ReadToEnd();
// do something with theString
}
Encoding.GetString Method (Byte[]) convert bytes to a string.
When overridden in a derived class, decodes all the bytes in the specified byte array into a string.
Namespace: System.Text
Assembly: mscorlib (in mscorlib.dll)
Syntax
public virtual string GetString(byte[] bytes)
Parameters
bytes
Type: System.Byte[]
The byte array containing the sequence of bytes to decode.
Return Value
Type: System.String
A String containing the results of decoding the specified sequence of bytes.
Exceptions
ArgumentException - The byte array contains invalid Unicode code points.
ArgumentNullException - bytes is null.
DecoderFallbackException - A fallback occurred (see Character Encoding in the .NET Framework for complete explanation) or DecoderFallback is set to DecoderExceptionFallback.
Remarks
If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks, the application should use the Decoder or the Encoder provided by the GetDecoder method or the GetEncoder method, respectively, of a derived class.
See the Remarks under Encoding.GetChars for more discussion of decoding techniques and considerations.
来源:https://stackoverflow.com/questions/6554869/byte-to-ascii