using (var file_stream = File.Create("users.xml"))
{
var serializer = new XmlSerializer(typeof(PasswordManager));
serializer.Serialize(file_stream, this);
file_stream.Close();
}
Using the above code works perfectly. However, when I shorten it to:
var serializer = new XmlSerializer(typeof(PasswordManager));
serializer.Serialize(File.Create("users.xml"), this);
I get the following exception when I try to deserialize the users.xml file in the same test:
The process cannot access the file ‘users.xml’ because it is being used by another process.
The cause seems to be that the the File.Create method returns an opened FileStream, that I cannot close as I do not hold onto a reference of it.
My bad, or Microsoft’s? 😉
The problem is that in your second example you open a file handle that you never dispose of, so the second time you call your method it will throw the exception you are describing. The first snippet is the preferable way (You could remove the file_stream.Close() bit – it will be automatically called by Stream.Dispose()).