写的.bin二进制文件 [英] Writing to .bin binary file

查看:197
本文介绍了写的.bin二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图整数写入二进制文件,但它一直在二进制文件给予奇怪的字符。例如,我尝试写2000,但在文件中我会得到一些奇怪的事情。如何解决呢?到处都找不到解决办法。

我用下面的code:

  //创建文件
        的FileStream FS =新的FileStream(iram.bin,FileMode.Create);
        //创建数据的作家。
        的BinaryWriter W =新的BinaryWriter(FS);w.Write((INT)2000);w.Close();
fs.Close();


解决方案

我认为这个问题是你没有读取数据回正常。

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

 使用(FS2的FileStream =新的FileStream(iram.bin,FileMode.Open))
    {
        使用(BinaryReader R =新BinaryReader(FS2))
        {
            变种integerValue = r.ReadInt32();
        }
    }

当然,除非你真的想将文本写入文件在这种情况下,你可能不希望一个的BinaryWriter将数据写出来。

如果你真的想写出你可以这样做这样的文字资料...(请务必您的编码设置成你所需要的)

 使用(VAR TW =新的StreamWriter(iram.txt,真实,Encoding.ASCII))
    {
        tw.WriteLine(2000);
    }

编辑:作为杰西提到你通常要在包装使用一次性块对象

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();

解决方案

I think the problem is that you are not reading the data back properly.

You will need to read the data back using a BinaryReader like so...

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

Unless of course you actually want to write text to the file in which case you probably don't want a BinaryWriter to write the data out.

If you actually want to write out text data you could do so like this... (Be sure to set your encoding to what you need)

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

Edit: As Jesse mentioned you normally want to wrap disposable objects in using blocks.

这篇关于写的.bin二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆