Force a write

  • Thread starter Thread starter MAF
  • Start date Start date
M

MAF

I am trying to save an XMLDocument and I occasionally get a sharing
violation. Can I force the write in this case?

System.Xml.XmlDocument XMLDoc = new System.Xml.XmlDocument();

//Load file

//Do something

XMLDoc.Save("c:\test.xml");
 
Sorry my mistake I forgot to close the reader. This code fixed the problem

System.IO.FileStream fin ;

fin = new System.IO.FileStream(@XMLDataFile, System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite) ;

XMLDoc.Load(new System.IO.StreamReader(fin)) ;

fin.Close();
 
MAF said:
Sorry my mistake I forgot to close the reader. This code fixed the problem

System.IO.FileStream fin ;

fin = new System.IO.FileStream(@XMLDataFile, System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite) ;

XMLDoc.Load(new System.IO.StreamReader(fin)) ;

fin.Close();

I would recommend using the using constructor for this:

using (FileStream fin = new FileStream (XMLDataFile,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
using (StreamReader reader = new StreamReader (fin))
{
XMLDoc.Load (reader);
}
}

While you don't *need* to close the reader, I generally think it's
better to dispose of everything that can be disposed.
 
Jon Skeet said:
I would recommend using the using constructor for this:

<snip>

Sorry, that should have been "the using construct" not "the using
constructor". Darned muscle memory :(
 
Back
Top