Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xml Serialization without Disposing

       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? ;-)

like image 693
Dabblernl Avatar asked May 17 '09 20:05

Dabblernl


People also ask

What is the correct way of using XML serialization?

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.

What is the basic difference between SOAP serialization and 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.

What does it mean to serialize XML?

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.

When should we use binary serialization as compared to XML serialization?

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.


1 Answers

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()).

like image 114
Darin Dimitrov Avatar answered Sep 19 '22 21:09

Darin Dimitrov