2

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

        }
Tony The Lion
  • 61,704
  • 67
  • 242
  • 415

4 Answers4

10

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • This is copied from a piece of production code, not written by me, that was failing to write to the file and I was attempting to debug it. Could you just tell me what is nasty about it? It really is supposed to take a memorystream and write the contents (a string) to a file... – Tony The Lion Jul 15 '10 at 09:48
  • This code forces the process to copy all of the contents of the `MemoryStream` (with the`ToArray()` call). See e.g. http://stackoverflow.com/questions/230128/best-way-to-copy-between-two-stream-instances-c for better methods. – Pontus Gagge Jul 15 '10 at 09:51
  • Thanks, so what does the ToArray call copy more then the method provided in your link? – Tony The Lion Jul 15 '10 at 10:18
  • @Tony: Use `MemoryStream.WriteTo` to do this in a much nicer fashion... and you don't need a `BinaryWriter` either. The code to populate the memory stream is somewhat wasteful too. – Jon Skeet Jul 15 '10 at 10:29
3

You are using the MemoryStream ms for both input and output. Change the line

using (BinaryWriter bw = new BinaryWriter(ms))

to

using (BinaryWriter bw = new BinaryWriter(fs))
tafa
  • 7,146
  • 3
  • 36
  • 40
0

Alternatively:

File.WriteAllText("myfile", "mytext");
Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
0

You are writing to text wtih the hardest way possible. you should use File.WriteAllText (as Adam says) or Append text method. 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.

NthDeveloper
  • 969
  • 8
  • 16