我有一個表示字節字符串表示
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 []編碼爲可以輕鬆寫入文本文件的字符串。 – 2011-03-03 01:53:40
當問題得到解答時,您可以將它們標記爲:) – PedroC88 2011-03-03 13:02:14