2009-06-02 63 views
1

我想顯示的字節數組中的文本文件內容的方式。的byte []字符串轉換似乎不工作,我想

這是我的代碼:

 var writer = new System.IO.StreamWriter(Application.StartupPath + @"\B323.txt"); 
     writer.Write(data.ToString()); 
     writer.Close(); 
     writer.Dispose(); 

數據是一個字節[]數組。

輸出爲 「System.Byte []」,爲什麼呢?

我試圖顯示此陣列的內容,哪裏出了問題?

回答

7

當你調用byte[].ToString()只返回System.Byte[]。你打算如何轉換字節數組?有多種將字節轉換爲字符串的方法。

如果你想把它當作一個「十六進制轉儲」你能不能BitConverter.ToString(byte[])這將產生輸出如

5B-3E-5D 

是你以後在做什麼?如果您實際上只想寫字節文件,因爲他們已經代表編碼的文本,那麼你應該使用一個FileStream,而不是和他們直接寫入。

(其他點作爲旁白:你應該使用一個using語句來處理的作家,你不需要調用close,因爲你已經處置; File.WriteAllText是這樣開始用一個簡單的方法。)

+0

我只希望知道爲什麼顯示「System.Byte []」是的,這就是我想要的,但我使用LINQ顯示空間,而不是characters.I之間的破折號只是想知道爲什麼它顯示System.Byte [] – 2009-06-02 13:00:37

3

調用上dataToString會把它變成一個文本表示(在調試的時候,你會在監視或局部變量窗口中看到相同的)。

您可以將data寫入流中,或者使用位於System.Text.Encoding的函數之一將字節[]轉換爲字符串。

3

默認toString()實現只是相呼應的類名。您可能需要Encoding.GetString()方法之一,如ASCIIEncoding.GetString

1

你想要做什麼?將數據寫入字節或作爲文本表示?

二進制:

FileStream fS = new FileStream(Application.StartupPath + @"\B323.txt"); 
BinaryWriter bW = new BinaryWriter(fS); 
bW.Write(data); 
fS.Close(); 

或者

文本表示:

var writer = new System.IO.StreamWriter(Application.StartupPath + @"\B323.txt"); 
writer.Write(System.Text.ASCIIEncoding.ASCII.GetString(data)); 
writer.Close(); 
1

取決於你如何想的陣列在文本文件中表示,也許像這些:

// 12-34-AB 
writer.Write(BitConverter.ToString(data)); 

// 1234AB 
writer.Write(BitConverter.ToString(data).Replace("-", string.Empty)); 

// 0x1234AB 
writer.Write("0x" + BitConverter.ToString(data).Replace("-", string.Empty)); 

// [ 12, 34, AB ] 
writer.Write("[ " + BitConverter.ToString(data).Replace("-", ", ") + " ]"); 

// [ 0x12, 0x34, 0xAB ] 
writer.Write("[ 0x" + BitConverter.ToString(data).Replace("-", ", 0x") + " ]");