Groups | Blog | Home
all groups > dotnet general > september 2006 >

dotnet general : Reading from XML to MemoryStream


Yehia A.Salam
9/30/2006 6:09:58 PM
Hello,

I am trying to read from an xml file and put it to a memory stream so I can
read it multiple times from the beginning using XmlTextReader without
accessing the harddisk , I tried using FileStream but it locked the xml file
so I can't access it anymore until I close the filestream, so my question is
how to read from the file to the memorystream directly or read to the
filestream first and the copy it to the memorystream?

Thanks
Yehia
Dave Sexton
10/1/2006 12:00:00 AM
Hi Yehia,

You might want to try loading the xml file into an XmlDocument instead of parsing it multiple times using a reader.
But if you want to use a MemoryStream then here's some code:

string file = @"C:\file.xml";

// .NET 2.0
byte[] bytes = System.IO.File.ReadAllBytes(file);

/* .NET 1.*
byte[] bytes = null;
using (System.IO.FileStream fileStream = new System.IO.FileStream(
file, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
System.IO.BinaryReader reader = new System.IO.BinaryReader(fileStream);
bytes = reader.ReadBytes((int) fileStream.Length);
}
*/

using (System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes))
{
System.Xml.XmlTextReader reader = System.Xml.XmlTextReader.Create(stream);
...
}

--
Dave Sexton

[quoted text, click to view]

Yehia A.Salam
10/2/2006 5:20:53 PM
but I read that XmlDocument is slow for large documents so I used
XmlTextReader,
what does "large" mean anyway? 1 MB, 100 MB, 500 MB?
my xml document is 1.5 Mb and has about 6000 element, is this considered
big? will be any performance hit using XmlDocument with this size of
document?


and another irrelevant question
string file = @"C:\file.xml"; --> what does @ mean
Dave Sexton
10/2/2006 11:38:00 PM
Hi Yehia,

Well I would suggest that you use XmlTextReader to save memory and only switch to XmlDocument if you start experiencing performance
problems that you can be sure are caused by multiple iterations of your source xml.


@ symbol in C# tells the compiler to treat the following string as a literal, without escapes.

"Hello\n" // = Hello{newline}
@"Hello\n" // = Hello\n
"Hello\"" // = Hello"
@"Hello\"" // won't compile because \ no longer escapes the "
@"Hello""" // = Hello" (double-quote becomes a single quote)

One great thing about @ is that you can use it on strings to span multiple lines in code and preserve the new lines:

string multiline = @"First Line
Second Line
Third Line";

--
Dave Sexton

[quoted text, click to view]

AddThis Social Bookmark Button