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? ;-)
XML Serialization Considerations Type identity and assembly information are not included. Only public properties and fields can be serialized. Properties must have public accessors (get and set methods). If you must serialize non-public data, use the DataContractSerializer class rather than XML serialization.
XML serialization can also be used to serialize objects into XML streams that conform to the SOAP specification. SOAP is a protocol based on XML, designed specifically to transport procedure calls using XML. To serialize or deserialize objects, use the XmlSerializer class.
XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.
Specific to . NET, If you have two applications that are using the same type system, then you can use binary serialization. On the other hand if you have applications that are in different platforms then it is recommended to use XML Serialization.
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()).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With