The World’s Leading Microsoft .NET Magazine
   
 
timstall

Donate Today!

Search Box

 

Calendar

««Mar 2010»»
SMTWTFS
  12
3
456
7
8
9
10
111213
14151617181920
21222324252627
28293031

My RSS Feeds








Mailing List

Most Popular Tags

                                                           

Convert from a MemoryStream to a string and back

posted Monday, 21 April 2008

A stream in .Net is a sequence of bytes. There are several types of streams. A common one is the MemoryStream which uses memory for its storage (as opposed to a file system, or something else). Several readers and writers require a stream as an input parameter, and you'll find that sometimes you'll just want to be able to easily convert from a string to a MemoryStream and back. Here are two easy utility methods to do that:

    public static string GetStringFromMemoryStream(MemoryStream m)
    {
      if (m == null || m.Length == 0)
        return null;

      m.Flush();
      m.Position = 0;
      StreamReader sr = new StreamReader(m);
      string s = sr.ReadToEnd();

      return s;
    }

    public static MemoryStream GetMemoryStreamFromString(string s)
    {
      if (s == null || s.Length == 0)
        return null;

      MemoryStream m = new MemoryStream();
      StreamWriter sw = new StreamWriter(m);
      sw.Write(s);
      sw.Flush();

      return m;
    }

 

We can easily test these with a round-trip method. Note that ideally we'd have one test for each specific method, but this is just for demo purposes:

 

    [TestMethod]
    public void Convert_RoundTrip()
    {
      string s1 = "Hello World!";
      MemoryStream m = GetMemoryStreamFromString(s1);

      Assert.AreEqual(12, m.Length);

      string s2 = GetStringFromMemoryStream(m);

      Assert.AreEqual(s1, s2);
    }

 

 

tags:    

links: digg this    technorati    




1. Matanel Sindilevich left...
Wednesday, 13 May 2009 5:04 pm

Hi! Regarding your implementation of the methods: 1. MemoryStream created and returned in the GetMemoryStreamFromString method is going to be set to the end of the stream by the StreamReader. Shouldn't you set it to the beginning of the stream, prior to passing it back to the caller?

2. Both GetStringFromMemoryStream and GetMemoryStreamFromString methods do not release StreamReader/StreamWriter objects they use. This leads to memory leaks, doesn't it?

3. Would the GetMemoryStreamFromString method release its StreamWriter object, prior passing the MemoryStream back to the caller, the MemoryStream object would render useless, as it will be reported "disposed". Wouldn't it be better for GetMemoryStreamFromString to return an array of bytes (byte[]), then creating a new MemoryStream object from that array in the caller later on?