<p>If I am given a <code>MemoryStream</code> that I know has been populated with a <code>String</code>, how do I get a <code>String</code> back out?</p>

[{'answer_id': 78189, 'author': 'Darren Kopp', 'author_id': 77, 'author_profile': 'https://Stackoverflow.com/users/77', 'pm_score': 6, 'selected': False, 'text': '<p>use a <a href="http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx" rel="nofollow noreferrer">StreamReader</a>, then you can use the <a href="http://msdn.microsoft.com/en-us/library/system.io.streamreader.readtoend.aspx" rel="nofollow noreferrer">ReadToEnd</a> method that returns a string.</p>\n'}, {'answer_id': 78190, 'author': 'Brian', 'author_id': 320, 'author_profile': 'https://Stackoverflow.com/users/320', 'pm_score': 7, 'selected': False, 'text': "<p>Using a StreamReader to convert the MemoryStream to a String.</p>\n\n<pre><code>&lt;Extension()&gt; _\nPublic Function ReadAll(ByVal memStream As MemoryStream) As String\n    ' Reset the stream otherwise you will just get an empty string.\n    ' Remember the position so we can restore it later.\n    Dim pos = memStream.Position\n    memStream.Position = 0\n\n    Dim reader As New StreamReader(memStream)\n    Dim str = reader.ReadToEnd()\n\n    ' Reset the position so that subsequent writes are correct.\n    memStream.Position = pos\n\n    Return str\nEnd Function\n</code></pre>\n"}, {'answer_id': 149993, 'author': 'Brian', 'author_id': 320, 'author_profile': 'https://Stackoverflow.com/users/320', 'pm_score': 10, 'selected': True, 'text': '<p>This sample shows how to read and write a string to a MemoryStream. </p>\n\n<hr>\n\n<pre><code>Imports System.IO\n\nModule Module1\n  Sub Main()\n    \' We don\'t need to dispose any of the MemoryStream \n    \' because it is a managed object. However, just for \n    \' good practice, we\'ll close the MemoryStream.\n    Using ms As New MemoryStream\n      Dim sw As New StreamWriter(ms)\n      sw.WriteLine("Hello World")\n      \' The string is currently stored in the \n      \' StreamWriters buffer. Flushing the stream will \n      \' force the string into the MemoryStream.\n      sw.Flush()\n      \' If we dispose the StreamWriter now, it will close \n      \' the BaseStream (which is our MemoryStream) which \n      \' will prevent us from reading from our MemoryStream\n      \'sw.Dispose()\n\n      \' The StreamReader will read from the current \n      \' position of the MemoryStream which is currently \n      \' set at the end of the string we just wrote to it. \n      \' We need to set the position to 0 in order to read \n      \' from the beginning.\n      ms.Position = 0\n      Dim sr As New StreamReader(ms)\n      Dim myStr = sr.ReadToEnd()\n      Console.WriteLine(myStr)\n\n      \' We can dispose our StreamWriter and StreamReader \n      \' now, though this isn\'t necessary (they don\'t hold \n      \' any resources open on their own).\n      sw.Dispose()\n      sr.Dispose()\n    End Using\n\n    Console.WriteLine("Press any key to continue.")\n    Console.ReadKey()\n  End Sub\nEnd Module\n</code></pre>\n'}, {'answer_id': 234262, 'author': 'Coderer', 'author_id': 26286, 'author_profile': 'https://Stackoverflow.com/users/26286', 'pm_score': 9, 'selected': False, 'text': "<p>You can also use</p>\n\n<pre><code>Encoding.ASCII.GetString(ms.ToArray());\n</code></pre>\n\n<p>I don't <em>think</em> this is less efficient, but I couldn't swear to it.  It also lets you choose a different encoding, whereas using a StreamReader you'd have to specify that as a parameter.</p>\n"}, {'answer_id': 2592074, 'author': 'James', 'author_id': 310910, 'author_profile': 'https://Stackoverflow.com/users/310910', 'pm_score': 3, 'selected': False, 'text': "<p>A slightly modified version of Brian's answer allows optional management of read start, This seems to be the easiest method.  probably not the most efficient, but easy to understand and use.</p>\n\n<pre><code>Public Function ReadAll(ByVal memStream As MemoryStream, Optional ByVal startPos As Integer = 0) As String\n    ' reset the stream or we'll get an empty string returned\n    ' remember the position so we can restore it later\n    Dim Pos = memStream.Position\n    memStream.Position = startPos\n\n    Dim reader As New StreamReader(memStream)\n    Dim str = reader.ReadToEnd()\n\n    ' reset the position so that subsequent writes are correct\n    memStream.Position = Pos\n\n    Return str\nEnd Function\n</code></pre>\n"}, {'answer_id': 13086317, 'author': 'Arek Bal', 'author_id': 1749204, 'author_profile': 'https://Stackoverflow.com/users/1749204', 'pm_score': 5, 'selected': False, 'text': '<p>Previous solutions wouldn\'t work in cases where encoding is involved. Here is - kind of a "real life" - example how to do this properly... </p>\n\n<pre class="lang-cs prettyprint-override"><code>using(var stream = new System.IO.MemoryStream())\n{\n  var serializer = new DataContractJsonSerializer(typeof(IEnumerable&lt;ExportData&gt;),  new[]{typeof(ExportData)}, Int32.MaxValue, true, null, false);               \n  serializer.WriteObject(stream, model);  \n\n\n  var jsonString = Encoding.Default.GetString((stream.ToArray()));\n}\n</code></pre>\n'}, {'answer_id': 26559972, 'author': 'Mehdi Khademloo', 'author_id': 4038978, 'author_profile': 'https://Stackoverflow.com/users/4038978', 'pm_score': 5, 'selected': False, 'text': '<p>In this case, if you really want to use <code>ReadToEnd</code> method in <code>MemoryStream</code> in an easy way, you can use this Extension Method to achieve this:</p>\n<pre class="lang-cs prettyprint-override"><code>public static class SetExtensions\n{\n    public static string ReadToEnd(this MemoryStream BASE)\n    {\n        BASE.Position = 0;\n        StreamReader R = new StreamReader(BASE);\n        return R.ReadToEnd();\n    }\n}\n</code></pre>\n<p>And you can use this method in this way:</p>\n<pre class="lang-cs prettyprint-override"><code>using (MemoryStream m = new MemoryStream())\n{\n    //for example i want to serialize an object into MemoryStream\n    //I want to use XmlSeralizer\n    XmlSerializer xs = new XmlSerializer(_yourVariable.GetType());\n    xs.Serialize(m, _yourVariable);\n\n    //the easy way to use ReadToEnd method in MemoryStream\n    MessageBox.Show(m.ReadToEnd());\n}\n</code></pre>\n'}, {'answer_id': 26892264, 'author': 'Alexandru', 'author_id': 982639, 'author_profile': 'https://Stackoverflow.com/users/982639', 'pm_score': 3, 'selected': False, 'text': "<p>Why not make a nice extension method on the MemoryStream type?</p>\n\n<pre><code>public static class MemoryStreamExtensions\n{\n\n    static object streamLock = new object();\n\n    public static void WriteLine(this MemoryStream stream, string text, bool flush)\n    {\n        byte[] bytes = Encoding.UTF8.GetBytes(text + Environment.NewLine);\n        lock (streamLock)\n        {\n            stream.Write(bytes, 0, bytes.Length);\n            if (flush)\n            {\n                stream.Flush();\n            }\n        }\n    }\n\n    public static void WriteLine(this MemoryStream stream, string formatString, bool flush, params string[] strings)\n    {\n        byte[] bytes = Encoding.UTF8.GetBytes(String.Format(formatString, strings) + Environment.NewLine);\n        lock (streamLock)\n        {\n            stream.Write(bytes, 0, bytes.Length);\n            if (flush)\n            {\n                stream.Flush();\n            }\n        }\n    }\n\n    public static void WriteToConsole(this MemoryStream stream)\n    {\n        lock (streamLock)\n        {\n            long temporary = stream.Position;\n            stream.Position = 0;\n            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8, false, 0x1000, true))\n            {\n                string text = reader.ReadToEnd();\n                if (!String.IsNullOrEmpty(text))\n                {\n                    Console.WriteLine(text);\n                }\n            }\n            stream.Position = temporary;\n        }\n    }\n}\n</code></pre>\n\n<p>Of course, be careful when using these methods in conjunction with the standard ones. :) ...you'll need to use that handy streamLock if you do, for concurrency.</p>\n"}, {'answer_id': 31437966, 'author': 'Sebastian Ferrari', 'author_id': 1231657, 'author_profile': 'https://Stackoverflow.com/users/1231657', 'pm_score': 4, 'selected': False, 'text': '<p>This sample shows how to read a string from a MemoryStream, in which I\'ve used a serialization (using DataContractJsonSerializer), pass the string from some server to client, and then, how to recover the MemoryStream from the string passed as parameter, then, deserialize the MemoryStream.</p>\n\n<p>I\'ve used parts of different posts to perform this sample.</p>\n\n<p>Hope that this helps.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Runtime.Serialization;\nusing System.Runtime.Serialization.Json;\nusing System.Threading;\n\nnamespace JsonSample\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var phones = new List&lt;Phone&gt;\n            {\n                new Phone { Type = PhoneTypes.Home, Number = "28736127" },\n                new Phone { Type = PhoneTypes.Movil, Number = "842736487" }\n            };\n            var p = new Person { Id = 1, Name = "Person 1", BirthDate = DateTime.Now, Phones = phones };\n\n            Console.WriteLine("New object \'Person\' in the server side:");\n            Console.WriteLine(string.Format("Id: {0}, Name: {1}, Birthday: {2}.", p.Id, p.Name, p.BirthDate.ToShortDateString()));\n            Console.WriteLine(string.Format("Phone: {0} {1}", p.Phones[0].Type.ToString(), p.Phones[0].Number));\n            Console.WriteLine(string.Format("Phone: {0} {1}", p.Phones[1].Type.ToString(), p.Phones[1].Number));\n\n            Console.Write(Environment.NewLine);\n            Thread.Sleep(2000);\n\n            var stream1 = new MemoryStream();\n            var ser = new DataContractJsonSerializer(typeof(Person));\n\n            ser.WriteObject(stream1, p);\n\n            stream1.Position = 0;\n            StreamReader sr = new StreamReader(stream1);\n            Console.Write("JSON form of Person object: ");\n            Console.WriteLine(sr.ReadToEnd());\n\n            Console.Write(Environment.NewLine);\n            Thread.Sleep(2000);\n\n            var f = GetStringFromMemoryStream(stream1);\n\n            Console.Write(Environment.NewLine);\n            Thread.Sleep(2000);\n\n            Console.WriteLine("Passing string parameter from server to client...");\n\n            Console.Write(Environment.NewLine);\n            Thread.Sleep(2000);\n\n            var g = GetMemoryStreamFromString(f);\n            g.Position = 0;\n            var ser2 = new DataContractJsonSerializer(typeof(Person));\n            var p2 = (Person)ser2.ReadObject(g);\n\n            Console.Write(Environment.NewLine);\n            Thread.Sleep(2000);\n\n            Console.WriteLine("New object \'Person\' arrived to the client:");\n            Console.WriteLine(string.Format("Id: {0}, Name: {1}, Birthday: {2}.", p2.Id, p2.Name, p2.BirthDate.ToShortDateString()));\n            Console.WriteLine(string.Format("Phone: {0} {1}", p2.Phones[0].Type.ToString(), p2.Phones[0].Number));\n            Console.WriteLine(string.Format("Phone: {0} {1}", p2.Phones[1].Type.ToString(), p2.Phones[1].Number));\n\n            Console.Read();\n        }\n\n        private static MemoryStream GetMemoryStreamFromString(string s)\n        {\n            var stream = new MemoryStream();\n            var sw = new StreamWriter(stream);\n            sw.Write(s);\n            sw.Flush();\n            stream.Position = 0;\n            return stream;\n        }\n\n        private static string GetStringFromMemoryStream(MemoryStream ms)\n        {\n            ms.Position = 0;\n            using (StreamReader sr = new StreamReader(ms))\n            {\n                return sr.ReadToEnd();\n            }\n        }\n    }\n\n    [DataContract]\n    internal class Person\n    {\n        [DataMember]\n        public int Id { get; set; }\n        [DataMember]\n        public string Name { get; set; }\n        [DataMember]\n        public DateTime BirthDate { get; set; }\n        [DataMember]\n        public List&lt;Phone&gt; Phones { get; set; }\n    }\n\n    [DataContract]\n    internal class Phone\n    {\n        [DataMember]\n        public PhoneTypes Type { get; set; }\n        [DataMember]\n        public string Number { get; set; }\n    }\n\n    internal enum PhoneTypes\n    {\n        Home = 1,\n        Movil = 2\n    }\n}\n</code></pre>\n'}, {'answer_id': 43770727, 'author': 'Sadjad Khazaie', 'author_id': 2116150, 'author_profile': 'https://Stackoverflow.com/users/2116150', 'pm_score': 5, 'selected': False, 'text': '<pre><code>byte[] array = Encoding.ASCII.GetBytes("MyTest1 - MyTest2");\nMemoryStream streamItem = new MemoryStream(array);\n\n// convert to string\nStreamReader reader = new StreamReader(streamItem);\nstring text = reader.ReadToEnd();\n</code></pre>\n'}, {'answer_id': 61205864, 'author': 'Riccardo Bassilichi', 'author_id': 218415, 'author_profile': 'https://Stackoverflow.com/users/218415', 'pm_score': 1, 'selected': False, 'text': '<p>I need to integrate with a class that need a Stream to Write on it:</p>\n\n<pre><code>XmlSchema schema;\n// ... Use "schema" ...\n\nvar ret = "";\n\nusing (var ms = new MemoryStream())\n{\n    schema.Write(ms);\n    ret = Encoding.ASCII.GetString(ms.ToArray());\n}\n//here you can use "ret"\n// 6 Lines of code\n</code></pre>\n\n<p>I create a simple class that can help to reduce lines of code for multiples use:</p>\n\n<pre><code>public static class MemoryStreamStringWrapper\n{\n    public static string Write(Action&lt;MemoryStream&gt; action)\n    {\n        var ret = "";\n        using (var ms = new MemoryStream())\n        {\n            action(ms);\n            ret = Encoding.ASCII.GetString(ms.ToArray());\n        }\n\n        return ret;\n    }\n}\n</code></pre>\n\n<p>then you can replace the sample with a single line of code </p>\n\n<pre><code>var ret = MemoryStreamStringWrapper.Write(schema.Write);\n</code></pre>\n'}, {'answer_id': 65290459, 'author': 'Harlin Acero', 'author_id': 8921881, 'author_profile': 'https://Stackoverflow.com/users/8921881', 'pm_score': -1, 'selected': False, 'text': '<p>Only use method Convert.ToBase64String</p>\n<pre><code>Convert.ToBase64String(inputStream.ToArray());\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/78181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/320/']