0

I need to open and XML file. The requirement is to be able to open it as read-only, and as read-write as well.

I tried the code below, but so far I can still write to the file.

var myFileStream = new FileStream(@"XMLFile.xml",FileMode.Open, FileAccess.Read, FileShare.Read);

var Reader = XmlReader.Create(myFileStream);
var XDoc = XDocument.Load(Reader, LoadOptions.PreserveWhitespace);
myFileStream.Close();
klce
  • 220
  • 3
  • 14

1 Answers1

0

You could wrap the XDocument object by following a pattern similar to the ReadOnlyXElement pattern detailed in Is there a way to create an immutable (read-only) XDocument?

To satisfy the read-write requirement, if you have a ReadOnlyXDocument wrapper class, I'd also be tempted to create a ReadWriteXDocument wrapper rather than using XDocument directly. This way the read-only/read-write distinction is obvious to any consuming code.

Community
  • 1
  • 1
Sam Meadley
  • 227
  • 1
  • 10