将二进制文件读入文本块

时间:2014-04-24 07:25:10

标签: c# wpf

我想将exe或任何二进制文件内容读入C#中的文本块。我有以下代码,但是当我开始阅读该文件时,应用程序卡住了。我的代码如下:

using (FileStream fs1 = new FileStream(FPath, FileMode.Open, FileAccess.Read))
{
    byte[] buf = new byte[1024];
    int size = 0;

    while ((size = fs1.Read(buf, 0, buf.Length)) > 0)
    {
        Console.Write("[" + buf.Length + "/" + size + "]");
        textBox.Text += encoding.default.getstring(buf)
    }
}

请指导我如何解决这个问题。

2 个答案:

答案 0 :(得分:2)

如果您只想阅读整个文件,可以使用File.ReadAllBytes

byte[] bytes = File.ReadAllBytes(FPath);
textBox.Text = Encoding.Default.GetString(bytes);

当你读取块时,那些可能不代表一个完整的可解码字符串:有时候字符需要多个字节,这些字符可能会以不同的块结束。

答案 1 :(得分:0)

您可以使用System.IO的StreamWriter类。 这是一个样本..

using( StreamReader sr = new StreamReader( FPath ) )
    {
        textBox.Text = sr.ReadToEnd( );
    }