C# Serialization lock out
- by Greycrow
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.