Writing a memory stream to a file

Coding Duchess picture Coding Duchess · Aug 17, 2015 · Viewed 66.7k times · Source

I have tried retrieving data in the json format as a string and writing it to a file and it worked great. Now I am trying to use MemoryStream to do the same thing but nothing gets written to a file - merely [{},{},{},{},{}] without any actual data.

My question is - how can I check if data indeed goes to memory stream correctly or if the problem occurs somewhere else. I do know that myList does contain data.

Here is my code:

MemoryStream ms = new MemoryStream();
DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(List<myClass>));
dcjs.WriteObject(ms, myList);

using (FileStream fs = new FileStream(Path.Combine(Application.StartupPath,"MyFile.json"), FileMode.OpenOrCreate))
{
                ms.Position = 0;
                ms.Read(ms.ToArray(), 0, (int)ms.Length);
                fs.Write(ms.ToArray(), 0, ms.ToArray().Length);
                ms.Close();
                fs.Flush();
                fs.Close();
 }

Answer

Philippe Par&#233; picture Philippe Paré · Aug 17, 2015

There is a very handy method, Stream.CopyTo(Stream).

using (MemoryStream ms = new MemoryStream())
{
    StreamWriter writer = new StreamWriter(ms);

    writer.WriteLine("asdasdasasdfasdasd");
    writer.Flush();

    //You have to rewind the MemoryStream before copying
    ms.Seek(0, SeekOrigin.Begin);

    using (FileStream fs = new FileStream("output.txt", FileMode.OpenOrCreate))
    {
        ms.CopyTo(fs);
        fs.Flush();
    }
}

Also, you don't have to close fs since it's in a using statement and will be disposed at the end.