簡體   English   中英

無法在c#中的文本框中正確顯示內容byte []

[英]unable to display contents byte[] properly on to a text box in c#

我試圖在文本框中顯示byte [],首先我正在從文件temp.enc中讀取所有加密信息到字節數組

FileStream f = File.OpenRead("temp.enc");
byte[] b = new byte[f.Length];//length is 32 bytes
f.Read(b, 0, Convert.ToInt32(f.Length));
f.Close();

第二,我嘗試在文本框中顯示內容,當我運行程序時,我看不到完整的數據。 它僅顯示數據的前23個字節

outputFileTextBox.Text = System.Text.Encoding.Default.GetString(b);

如果我再次使用相同的字節數組將信息寫回到文件中,又如何將所有32bytes寫入文件

BinaryWriter swEnc = new BinaryWriter(File.OpenWrite("encypt.txt"));
swEnc.Write(b);
swEnc.Close();

這是一個ac#Windows應用程序,我不確定我在做什么錯。

確保以相同格式讀取和寫入。 看起來您正在使用TEXT(默認)編碼作為TEXT讀取,但是您以Binary格式將其寫回。

這是一個示例代碼,它以與讀入時相同的格式寫回:

    private string ReadFile(string filename)
    {
        var sb = new StringBuilder();
        if (System.IO.File.Exists(filename))
        {
            using (var f = System.IO.File.OpenRead(filename))
            {
                var b = new byte[f.Length];
                var len = f.Read(b, 0, b.Length);
                while ((-1 < len) && (len == b.Length))
                {
                    sb.Append(System.Text.Encoding.UTF8.GetString(b, 0, len));
                    len = f.Read(b, 0, b.Length);
                }
            }
        }
        return sb.ToString();
    }

    private void WriteFile(string filename, string data)
    {
        using (var f = System.IO.File.OpenWrite(filename))
        {
            var b = System.Text.Encoding.UTF8.GetBytes(data);
            f.Write(b, 0, b.Length);
        }
    }

此外,某些TEXT字符可能是非打印值(回車,字段開始,字段結束等)。

在下面的ASCII圖表中,考慮所有低於十進制32值的不可顯示值:

ASCII圖表

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM