difference between memory stream and filestream

Raghav55 picture Raghav55 · Nov 16, 2011 · Viewed 90.6k times · Source

During the serialization we can use either memory stream or file stream.

What is the basic difference between these two? What does memory stream mean?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;

namespace Serilization
{
    class Program
    {
        static void Main(string[] args)
        {
            MemoryStream aStream = new MemoryStream();
            BinaryFormatter aBinaryFormat = new BinaryFormatter();
            aBinaryFormat.Serialize(aStream, person);
            aStream.Close();
        }
    }
}

Answer

Enigma State picture Enigma State · Nov 16, 2011

Stream is a representation of bytes. Both these classes derive from the Stream class which is abstract by definition.

As the name suggests, a FileStream reads and writes to a file whereas a MemoryStream reads and writes to the memory. So it relates to where the stream is stored.

Now it depends how you plan to use both of these. For eg: Let us assume you want to read binary data from the database, you would go in for a MemoryStream. However if you want to read a file on your system, you would go in for a FileStream.

One quick advantage of a MemoryStream is that there is not need to create temporary buffers and files in an application.