I need to open an XML file exclusively, make a modification, and save it.
I can open it and make the modification pretty easily like so:
DataSet ds = new DataSet();
ds.ReadXml(filename);
DataTable table = ds.Tables[0];
DataRow[] rows = table.Select("Inventory== 1");
DataRow row = rows[0];
row["Inventory"] = "2";
ds.WriteXml(filename);
That all works great, but it doesn't lock the file. I absolutely need the file locked.
So I tried it with a stream:
FileStream stream = File.Open(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
DataSet ds = new DataSet();
ds.ReadXml(stream);
DataTable table = ds.Tables[0];
DataRow[] rows = table.Select("Inventory== 1");
DataRow row = rows[0];
row["Inventory"] = "2";
ds.WriteXml(stream);
stream.Close();
That opens the file exclusively, but when it saves, it appends the XML to the end of the time, it doesn't overwrite it, so I end up with something like:
<Widgets>
<Widget Code="5" Number="10" Inventory="1" />
<Widget Code="6" Number="11" Inventory="15" />
<Widget Code="7" Number="12" Inventory="22" />
</Widgets>
<Widgets>
<Widget Code="5" Number="10" Inventory="2" />
<Widget Code="6" Number="11" Inventory="15" />
<Widget Code="7" Number="12" Inventory="22" />
</Widgets>
What I want is:
<Widgets>
<Widget Code="5" Number="10" Inventory="2" />
<Widget Code="6" Number="11" Inventory="15" />
<Widget Code="7" Number="12" Inventory="22" />
</Widgets>
I know I could open the file and use the File methods to parse it line by line and make my change... but I was hoping for something more elegant. The first method - loading the file using ReadXml - does the file modification just fine, but it doesn't appear to have any options for opening the file exclusively. Am I missing something?