12

Right now I'm using XmlTextWriter to convert a MemoryStream object into string. But I wan't to know whether there is a faster method to serialize a memorystream to string.

I follow the code given here for serialization - http://www.eggheadcafe.com/articles/system.xml.xmlserialization.asp

Edited

Stream to String

ms.Position = 0;
using (StreamReader sr = new StreamReader(ms))
{
    string content = sr.ReadToEnd();
    SaveInDB(ms);
}

String to Stream

string content = GetFromContentDB();
byte[] byteArray = Encoding.ASCII.GetBytes(content);
MemoryStream ms = new MemoryStream(byteArray); 
byte[] outBuf = ms.GetBuffer(); //error here
Mark Rucker
  • 6,952
  • 4
  • 39
  • 65
NLV
  • 21,141
  • 40
  • 118
  • 183
  • Possible duplicate of [How do you get a string from a MemoryStream?](http://stackoverflow.com/questions/78181/how-do-you-get-a-string-from-a-memorystream) – Michael Freidgeim Mar 23 '16 at 12:26

2 Answers2

29
using(MemoryStream stream = new MemoryStream()) {
   stream.Position = 0;
   var sr = new StreamReader(stream);
   string myStr = sr.ReadToEnd();
}

You cant use GetBuffer when you use MemoryStream(byte[]) constructor.

MSDN quote:

This constructor does not expose the underlying stream. GetBuffer throws UnauthorizedAccessException.

You must use this constructor and set publiclyVisible = true in order to use GetBuffer

NLV
  • 21,141
  • 40
  • 118
  • 183
Stecya
  • 22,896
  • 10
  • 72
  • 102
  • I'm afraid this is not giving the write string. After I try to convert the string back to memory stream it is throwing error message "MemoryStream's internal buffer cannot be accessed." while doing memorystream.GetBuffer(). – NLV May 28 '11 at 12:50
  • Have updated the code in the post. The original Memory stream is around 95000 bytes. But after I convert the string back to stream I'm getting only 1900 bytes. – NLV May 28 '11 at 13:21
  • 1
    Possibly a stupid question, but are you sure that the database field is big enough? Does the conversion work if you store it in memory instead of the DB? – Matthew Steeples May 28 '11 at 13:28
  • @Matthew I too have the same doubt. I'm investigating on that right now since I'm using a library that does not expose the schema of the database to me. – NLV May 28 '11 at 13:34
  • Oops. Storing/retrieval of the string is the problem. I'm not able to retrieve the full string from the DB as the max capacity of the column is less. Just did a quick check of the string length before saving it and after retrieving it. Will sort it out. – NLV May 28 '11 at 13:40
3

In VB.net i used this

Dim TempText = System.Text.Encoding.UTF8.GetString(TempMemoryStream.ToArray())

in C# may apply

Esteban Perez
  • 390
  • 3
  • 5