Can't write to file using binarywriter

Tony The Lion picture Tony The Lion · Jul 15, 2010 · Viewed 8.1k times · Source

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

        }

Answer

Jon Skeet picture Jon Skeet · Jul 15, 2010

Look at this line:

using (BinaryWriter bw = new BinaryWriter(ms))

You're writing back to the 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.