Sunday, 28 December 2014

Sharing violation on program-generated xml file



I am writing a C# console application using monodevelop, and I recently decided to use an xml file as way of storing user preferences. Creating, writing the initial data, and reading the file are easily accomplished, and from what I've seen updating it should be too. However, the code below generates a Sharing violation on path:



public void Update (string username, PreferenceAttribute preferencename, string newvalue)
{
try
{
...
//this is where it throws exception \/
using (FileStream fs = new FileStream (filepath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
string attribute = preferencename.ToString ();
doc = new XmlDocument ();
doc.Load (fs);
fs.Close ();
XmlNode user = doc.SelectSingleNode ("//Users/User[@Name = '" + username + "']");
user = user.SelectSingleNode("Pref");
user.Attributes[attribute].Value = newvalue;
doc.Save (fs);
}
} catch (Exception ex)
{
//error details output
}
}


Leaving out the using block causes the error to happen at the doc.save(fs) line and also results in the file losing any data it had. I've looked at other posts, but the only solutions seem to be the using block. I need a way to get the lock on the file (unless my code is generating the problem). Any help?


No comments:

Post a Comment