Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a memory stream to a file

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();
 }
like image 829
Coding Duchess Avatar asked Aug 17 '15 15:08

Coding Duchess


People also ask

How do I write a memory stream file?

One solution to that is to create the MemoryStream from the byte array - the following code assumes you won't then write to that stream. MemoryStream ms = new MemoryStream(bytes, writable: false); My research (below) shows that the internal buffer is the same byte array as you pass it, so it should save memory.

What is a memory stream?

MemoryStream encapsulates data stored as an unsigned byte array. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application. The current position of a stream is the position at which the next read or write operation takes place.

How do I use MemoryStream?

This code shows how to use MemoryStream class and its member to read data in memory stream, which can be used to save it from there. int count; //GetByteData function to get Byte data like if you fetch Image column data from sqlserver or somewhere. byte[] byteArray = getByteData();


1 Answers

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.

like image 74
Philippe Paré Avatar answered Oct 12 '22 22:10

Philippe Paré