Sunday, April 20, 2008

Convert from a MemoryStream to a string and back

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/convert_from_a_memorystream_to_a_string_and_back.htm]

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

 

 

No comments:

Post a Comment