0

I am trying to write integer numbers to binary file, but it keeps giving weird characters in the binary file. For example, I try to write 2000, but in the file i will get something strange. How do I fix it? Couldn't find the solution anywhere.

I use the following code:

 //create the file
        FileStream fs = new FileStream("iram.bin", FileMode.Create);
        // Create the writer for data.
        BinaryWriter w = new BinaryWriter(fs);

w.Write((int) 2000);

w.Close();
fs.Close();
4

2 回答 2

4

我认为问题在于您没有正确读取数据。

您将需要像这样使用 BinaryReader 读回数据...

    using (FileStream fs2 = new FileStream("iram.bin", FileMode.Open))
    {
        using(BinaryReader r = new BinaryReader(fs2))
        {
            var integerValue = r.ReadInt32();
        }
    }

当然,除非您确实想将文本写入文件,在这种情况下,您可能不希望 BinaryWriter 将数据写出。

如果你真的想写出文本数据,你可以这样做......(确保将你的编码设置为你需要的)

    using (var tw = new StreamWriter("iram.txt", true, Encoding.ASCII))
    {
        tw.WriteLine(2000);
    }

编辑:正如 Jesse 提到的,您通常希望将一次性物品包装在 using 块中。

于 2013-05-14T21:07:24.123 回答
1

您在文件中获得意外字符的原因是因为您写入文件的内容并不意味着首先被解释为字符序列

当您在记事本或其他文本编辑器中打开它时,它只会获取那里的内容,猜测编码(或使用默认值),并向您显示数据将编码的任何字符(如果它是编码字符)。它不是为了人类可读的。


具有字符序列的人类可读文本文件2000实际上具有字符的编码2,然后是03倍的编码。

在 Unicode 中是U+0032U+0030U+0030U+0030

于 2013-05-14T21:07:29.810 回答