简体   繁体   English

无法使用二进制文件写入文件

[英]Can't write to file using binarywriter

Why does this code not write my string to the file: 为什么这段代码不会将我的字符串写入文件:

 string file = "Myfile.txt";
        MemoryStream ms = new MemoryStream();

void writeToFile(string text)
        {
            System.Text.ASCIIEncoding  encoding=new System.Text.ASCIIEncoding();
            byte[] barr = encoding.GetBytes(text);


            ms.Write(barr, 0, barr.Length);

            using (FileStream fs = new FileStream(file, FileMode.OpenOrCreate))
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    bw.Write(ms.ToArray());
                }
            }
        }


        static void Main(string[] args)
        {

            Program p = new Program();

            p.writeToFile("Tony Test");

            Console.ReadLine();

        }

Look at this line: 看看这一行:

using (BinaryWriter bw = new BinaryWriter(ms))

You're writing back to the MemoryStream . 你正在写回MemoryStream You want: 你要:

using (BinaryWriter bw = new BinaryWriter(fs))

Having said that, this is a pretty nasty way of writing to a file, with all kinds of unnecessary steps. 话虽如此,这是一种非常讨厌的写入文件的方式,有各种不必要的步骤。 Hopefully this was just experimentation trying to work out why something else wasn't working - but if your real code is actually like this, please give details of what you're trying to do and we can help you tidy it up. 希望这只是尝试解决为什么其他东西不起作用的实验 - 但如果您的真实代码实际上是这样的,请详细说明您正在尝试做什么,我们可以帮助您整理它。

You are using the MemoryStream ms for both input and output. 您正在使用MemoryStream ms进行输入和输出。 Change the line 改变线

using (BinaryWriter bw = new BinaryWriter(ms))

to

using (BinaryWriter bw = new BinaryWriter(fs))

或者:

File.WriteAllText("myfile", "mytext");

You are writing to text wtih the hardest way possible. 你正在用最难的方式写文字。 you should use File.WriteAllText (as Adam says) or Append text method. 你应该使用File.WriteAllText(如Adam所说)或附加文本方法。 If you want to use a writer with special encoding than you should use StreamWriter, since it works with text data and you can set the Encoding of the file. 如果要使用具有特殊编码的编写器,则应使用StreamWriter,因为它可以处理文本数据,您可以设置文件的编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM