Reading from XML to MemoryStream

Y

Yehia A.Salam

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
 
D

Dave Sexton

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);
...
}
 
Y

Yehia A.Salam

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
 
D

Dave Sexton

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";
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top