2010-10-14 89 views
0

編輯:不要回答;我自己找到了解決方案。.NET:讀寫二進制字符串

我有一些代碼,這是否:

using (var stream = new FileStream(args[1], FileMode.Create)) 
{ 
using (var writer = new BinaryWriter(stream)) 
{ 
    writer.Write(ip.Iso3166CountryCode); 
    ... 
} 
} 

Iso3166CountryCodestring有兩個字符( 「US」)。

當我嘗試從文件中讀取「US」:

// line is a byte[] from the file with the first 1024 bytes 
UnicodeEncoding.Default.GetString(line.Take(2).ToArray()); 

我不明白「美」後,我得到一些奇怪的ASCII字符後面。如何從這個二進制文件讀取兩個國家代碼字符?

編輯:從來沒有想過。我將writer.Write(ip.Iso3166CountryCode)更改爲writer.Write(UnicodeEncoding.Default.GetBytes(ip.Iso3166CountryCode)),它工作。

+0

您可以回答自己的問題,並將其標記爲已接受。這比編輯你的問題獲得答案要好。 – softveda 2010-10-14 05:44:31

+0

否則刪除你的問題..... – 2010-10-14 05:54:41

回答

1

嘗試更改writer.Write(ip.Iso3166CountryCode)writer.Write(UnicodeEncoding.Default.GetBytes(ip.Iso3166CountryCode)),這應該工作! :)

+0

呃,這是我發佈的確切解決方案,在你的答案之前。 – CantSleepAgain 2010-10-14 08:07:27

+1

好吧,笑臉有點小 - 我看到「不回答」,我的鼠標開始複製粘貼在自己身上...... – 2010-10-14 13:54:14