【发布时间】:2011-09-27 03:30:40
【问题描述】:
我收到了以二进制值返回的文本文件的内容:
Byte[] buf = new Byte[size];
stream = File.InputStream;
stream.Read(buf, 0, size);
如何将其转换为 ASCII?
【问题讨论】:
标签: c# .net file-upload bitconverter
我收到了以二进制值返回的文本文件的内容:
Byte[] buf = new Byte[size];
stream = File.InputStream;
stream.Read(buf, 0, size);
如何将其转换为 ASCII?
【问题讨论】:
标签: c# .net file-upload bitconverter
【讨论】:
ASCIIEncoding.GetString(byte[] bytes, int byteIndex, int byteCount)(或没有第三个参数直到缓冲区结束) . (您可以在答案中包含此信息,以获得更全面的答案,尽管没有明确要求。)
你可以使用:
System.Text.Encoding.ASCII.GetString(buf);
但有时你会得到一个奇怪的数字而不是你想要的字符串。在这种情况下,当您看到原始字符串时,它可能包含一些十六进制字符。如果是这种情况,您可能想试试这个:
System.Text.Encoding.UTF8.GetString(buf);
或者作为最后的手段:
System.Text.Encoding.Default.GetString(bytearray);
【讨论】:
Encoding.ASCII.GetString(buf);
【讨论】:
作为将数据从流中读取到字节数组的替代方法,您可以让框架处理所有内容,只需使用带有 ASCII 编码的StreamReader 设置来读取字符串。这样您就不必担心获得适当的缓冲区大小或更大的数据大小。
using (var reader = new StreamReader(stream, Encoding.ASCII))
{
string theString = reader.ReadToEnd();
// do something with theString
}
【讨论】:
Encoding.GetString Method (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 进行更多讨论 解码技术和 考虑。
【讨论】: