【发布时间】:2011-03-03 01:21:53
【问题描述】:
我有一个代表一个字节的字符串
string s = "\x00af";
我将此字符串写入文件,因此文件包含文字“\x00af”而不是它所代表的字节,后来我从文件中读取了这个字符串,我现在如何再次将此字符串视为字节(而不是文字)?
这是一个示例代码:
public static void StringAndBytes()
{
string s = "\x00af";
byte[] b = Encoding.ASCII.GetBytes(s);
// Length would be 1
Console.WriteLine(b.Length);
// Write this to a file as literal
StreamWriter sw = new StreamWriter("c:\\temp\\MyTry.txt");
sw.WriteLine("\\x00af");
sw.Close();
// Read it from the file
StreamReader sr = new StreamReader("c:\\temp\\MyTry.txt");
s = sr.ReadLine();
sr.Close();
// Get the bytes and Length would be 6, as it treat the string as string
// and not the byte it represents
b = Encoding.ASCII.GetBytes(s);
Console.WriteLine(b.Length);
}
关于如何将字符串从文本转换为表示字节的字符串的任何想法?谢谢!
【问题讨论】:
-
别这样写。您不需要编写 C# 编译器来读回它。并且永远不要将字节存储在字符串中,并非所有字节值都是合法的 Unicode 字符。使用 Convert.ToBase64String 将 byte[] 编码为可以轻松写入文本文件的字符串。
-
当问题得到回答时,您可以将它们标记为 ;)