Liquidkristal
Liquidkristal

Reputation: 157

Loading XML into a memorystream

SO I am trying to get a simple dataset from the strInstallDataSet string into the dataset, using the code below, when I have the debugger connected I can see that strInstallDataSet has data, byteArray has data, but even after reading msDataset has nothing, length just sits at 0, I have tried setting the position before and after reading but it still just doesn't pick up any data. Any ideas?

MemoryStream msDataset = new MemoryStream();

if (strInstallDataSet != null)
    {
        // Convert string to byte array.
        byte[] byteArray = Encoding.ASCII.GetBytes(strInstallDataSet);
        msDataset.Read(byteArray, 0, byteArray.Length);

        // Put stream back into dataset object.
        dsInstallData.ReadXml(msDataset);

        msDataset.Close();
        msDataset.Dispose();
    }

Upvotes: 2

Views: 7178

Answers (4)

Adilson de Almeida Jr
Adilson de Almeida Jr

Reputation: 2755

You must use Write method instead of read. I think you want to write your bytearray into your memory stream.

Upvotes: 0

CodingGorilla
CodingGorilla

Reputation: 19842

You probably want to be doing the following:

using(StringReader reader = new StringReader(strInstallDataSet)) 
{
    dsInstallData.ReadXml(reader);
}

Upvotes: 3

Jimmy Hoffa
Jimmy Hoffa

Reputation: 5967

You're misunderstanding what the MemoryStream.Read() does, it reads into the byte array, not into the memorystream.

You want MemoryStream.Write() where you have MemoryStream.Read()

Or better yet...

MemoryStream xmlMemoryStream = new MemoryStream(byteArray);

Upvotes: 0

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

You are not writing anything to the stream, only reading msDataset.Read...

Side note 1: you are using very low level methods - there are Reader/Writer classes that will correctly take care of encoding already.

Side note 2: use "using" instead of manually calling Close or Dispose (and don't call 2 of them together as both do exactly the same things).

Upvotes: 0

Related Questions