C# Serialization lock out
Posted
by Greycrow
on Stack Overflow
See other posts from Stack Overflow
or by Greycrow
Published on 2010-03-13T05:06:48Z
Indexed on
2010/03/13
5:15 UTC
Read the original article
Hit count: 337
c#
|xml-serialization
When I try to Serialize a class to an xml file I get the exception: The process cannot access the file 'C:\settings.xml' because it is being used by another process.
Settings currentSettings = new Settings();
public void LoadSettings()
{
//Load Settings from XML file
try
{
Stream stream = File.Open("settings.xml", FileMode.Open);
XmlSerializer s = new XmlSerializer(typeof(Settings));
currentSettings = (Settings)s.Deserialize(stream);
stream.Close();
}
catch //Can't read XML - use default settings
{
currentSettings.Name = GameSelect.Items[0].ToString();
currentSettings.City = MapSelect.Items[0].ToString();
currentSettings.Country = RaceSelect.Items[0].ToString();
}
}
public void SaveSettings()
{
//Save Settings to XML file
try
{
Stream stream = File.Open("settings.xml", FileMode.Create);
XmlSerializer x = new XmlSerializer(typeof(Settings));
x.Serialize(stream, currentSettings);
stream.Close();
}
catch
{
MessageBox.Show("Unable to open XML File - File in use by other process");
}
It appears that when I Deserialize it locks the file for writing back, even if I closed the stream.
Thanks in advance.
© Stack Overflow or respective owner