Continuous XmlSerializer (partially) null file

I am using XmlSerializer with StreamWriter as follows:

... string xmlFile = GetXMLLocation(objToSaveType); XmlSerializer Serializer = new XmlSerializer(objToSaveType); using (StreamWriter sw = new StreamWriter(xmlFile)) Serializer.Serialize(sw, objToSave); ... 

This works the vast majority of the time, but the rarely generated file is filled with null characters, and from time to time the intruder file ends with only null characters, for example.

 ... <Extension>0</Extension> </OrderProductLine> <OrderProductLine> <ProductDescription /> <Commission>0.3</Commission> <UnitType /> <UnitPrice>0</UnitPrice> <UnitQuantity>0</UnitQuantity> <PackageType /> <Extension>0</Extension> [null x ~1 million] 

I could never reproduce it myself. It does not generate any errors during serialization and, apparently, appears only during the program shutdown.

Related questions:

  • here is an obvious correction; the writer is not washed off; I use using , which calls Dispose (), which matches Close ()
  • here - the best answer suggests that the error was missed; I have no error; an empty file and one filled with zeros do not match. However, one answer suggests that this is a caching issue.

I changed my code as follows if the idea of ​​caching the question is correct:

 string xmlFile = GetXMLLocation(objToSaveType); XmlSerializer Serializer = new XmlSerializer(objToSaveType); using (Stream file = new FileStream(xmlFile, FileMode.Create, FileAccess.Write, FileShare.None, 0x1000, FileOptions.WriteThrough)) using (StreamWriter sw = new StreamWriter(file)) Serializer.Serialize(sw, objToSave); 

I have some ideas on workarounds (mainly deserialize right after saving, rolling back, or try again if there is a problem), but it would be great to fix this thing. Since this is so intermittent, I still don't know if this is fixed above or not. This post should either inform others in a similar situation about a possible fix, or get ideas for other possible reasons. Thanks for reading. (PS First SO post, sorry if I broke any protocols!)

Update: just over a week later, the error has not yet appeared. My fingers are crossed, although it really will take me about a month to know with sufficient confidence if these are fixed things.

Update: two and a half weeks later, still good.

Hopefully the latest update: a month later is still good. Caching seemed to be a problem after all, yay!

+4
source share
1 answer

I talked with a colleague about what we did to fix this problem in our application.

We saved some XML data when the application closed, and it looks like the stream that writes the file to disk is killed by the application shutdown process.

We moved the save command from the application close window until the data was changed. This solved the problem for us.

0
source

All Articles