Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I clone MemoryStream object?

I have a MemoryStream object which is passed by Stream type parameter
(Stream is abstract class in C#).

I want to clone him and to create another MemoryStream object a side with current position of the original and to create also a new XMLReader out of it, so I will be able to read its content.

This is what I did, and it's not working (debugging the line marked with //* -> newReader has got {None} value)
Assumption: you are inside a method and have Stream currentStream reference.

var x = new XmlReaderSettings();
x.IgnoreWhitespace = true;  

 using (var newMemoryStream = new MemoryStream())
 {
         stream.CopyTo(newMemoryStream);

         using (var newReader = XmlReader.Create(newMemoryStream,x)) //*
         {

           Doing some stuff...

         }
 }
like image 237
JavaSa Avatar asked Dec 19 '12 22:12

JavaSa


People also ask

How do I reuse MemoryStream?

You can re-use the MemoryStream by Setting the Position to 0 and the Length to 0. By setting the length to 0 you do not clear the existing buffer, it only resets the internal counters.

How do you save on MemoryStream?

Save MemoryStream to a String Steps follows.. StreamWriter sw = new StreamWriter(memoryStream); sw. WriteLine("Your string to Memoery"); This string is currently saved in the StreamWriters buffer.

What is MemoryStream in .NET core?

MemoryStream encapsulates data stored as an unsigned byte array that is initialized upon creation of a MemoryStream object, or the array can be created as empty. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application.


1 Answers

Make sure to reset the position on newMemoryStream like so:

newMemoryStream.Position = 0;

after stream.CopyTo(newMemoryStream); but before creating the XmlReader

So the whole thing should look like this:

var x = new XmlReaderSettings();
x.IgnoreWhitespace = true;  

using (var newMemoryStream = new MemoryStream())
{
    stream.CopyTo(newMemoryStream);
    newMemoryStream.Position = 0;

    using (var newReader = XmlReader.Create(newMemoryStream,x)) //*
    {
        Doing some stuff...
    }
}

Also, since you're using another reader on the original stream prior to entering this method, make sure that the Position of the source stream is really where you want it to be.

like image 198
mlorbetske Avatar answered Oct 15 '22 07:10

mlorbetske