我收到了一个文本文件的内容以二进制值返回:
Byte[] buf = new Byte[size];
stream = File.InputStream;
stream.Read(buf, 0, size);
我该如何将这个转换为ASCII码?
我收到了一个文本文件的内容以二进制值返回:
Byte[] buf = new Byte[size];
stream = File.InputStream;
stream.Read(buf, 0, size);
我该如何将这个转换为ASCII码?
你可以使用:
System.Text.Encoding.ASCII.GetString(buf);
但有时你可能得到一个奇怪的数字而不是你想要的字符串。在这种情况下,你原来的字符串可能包含一些十六进制字符。如果是这样的话,你可以尝试这个方法:
System.Text.Encoding.UTF8.GetString(buf);
如果别无选择:
System.Text.Encoding.Default.GetString(bytearray);
buf2 = Encoding.ASCII.GetBytes(Encoding.ASCII.GetString(buf))
,它是否与 buf
相同? - John HenckelEncoding.ASCII.GetString(buf);
StreamReader
读取字符串,而不是从流中读取数据到字节数组。这样您就无需担心获取适当的缓冲区大小或更大的数据大小。using (var reader = new StreamReader(stream, Encoding.ASCII))
{
string theString = reader.ReadToEnd();
// do something with theString
}
Encoding.GetString 方法 (Byte[]) 将字节数组转换为字符串。
在派生类中重写时,将指定的字节数组中的所有字节解码为字符串。
命名空间: System.Text
程序集: mscorlib (mscorlib.dll 中)
语法
public virtual string GetString(byte[] bytes)
参数
bytes
Type: System.Byte[]
The byte array containing the sequence of bytes to decode.
返回值
类型: System.String
一个字符串,包含解码指定字节序列的结果。
异常
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.
备注
如果要转换的数据仅以连续块的形式可用(例如从流中读取的数据),或者如果数据量太大,需要将其分成较小的块,则应用程序应使用派生类的GetDecoder方法或GetEncoder方法提供的解码器或编码器。
有关解码技术和注意事项的更多讨论,请参见Encoding.GetChars下的备注。
ASCIIEncoding.GetString(byte[] bytes, int byteIndex, int byteCount)
(或者没有第三个参数,直到缓冲区的末尾)。(您可以在答案中包含此信息,以获得更全面的答案,但并未明确要求。) - Peter Mortensen