Serialize an object to XMLI will start with the copy answer of Ben Gripka: public void Save(string File. Name). using (var writer = new System. IO. Stream. Writer(File. Name)). var serializer = new Xml. A curated list of awesome Go frameworks, libraries and software. Then convert the DataTable into a JSON object using any of the previous methods that return the JSON object. Let’s go through each method step-by-step.
![]() Serializer(this. Get. Type()). serializer. Serialize(writer, this). Flush(). I used this code earlier. But reality showed that this solution is a bit problematic. Usually most of programmers just serialize setting on save and deserialize settings on load. This is an optimistic scenario. Once the serialization failed, because of some reason, the file is partly written, XML file is not complete and it is invalid. In consequence XML deserialization does not work and your application may crash on start. If the file is not huge, I suggest first serialize object to Memory. Stream then write the stream to the File. This case is especially important if there is some complicated custom serialization. You can never test all cases. Save(string file. Name). //first serialize the object to memory stream. Memory. Stream ms = new Memory. Stream()). var writer = new System. IO. Stream. Writer(ms). Xml. Serializer(this. Get. Type()). serializer. Serialize(writer, this). Flush(). //if the serialization succeed, rewrite the file. File. Write. All. Bytes(file. Name, ms. To. Array()). The deserialization in real world scenario should count with corrupted serialization file, it happens sometime. Load function provided by Ben Gripka is fine. Object. Type] Load(string file. Name). using (var stream = System. IO. File. Open. Read(file. Name)). var serializer = new Xml. Serializer(typeof([Object. Type])). return serializer. Deserialize(stream) as [Object. Type]. And it could be wrapped by some recovery scenario. It is suitable for settings files or other files which can be deleted in case of problems. Object. Type] Load. With. Recovery(string file. Name). return Load(file. Name). catch(Excetion). File. Delete(file. Name); //delete corrupted settings file. Get. Factory. Settings().
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
November 2017
Categories |