Feedback

C# - Easy XML Serializing and Deserializing

Veröffentlicht von am 10/25/2013
(2 Bewertungen)
This snippet makes XML serializing and deserializing very easy

Dieses Snippet macht die XML serialisierung und deserialisierung sehr einfach

Published for http://splitporn.com

Anwendung | Usage:
// A simple test class
// Eine einfache Testklasse
public class Person
{
public string Name;
public int Age;
}

// Write the class to a xml file
// Schreibe die Klasse in eine XML datei
Person person = new Person ();
person.Name = "Splitty";
person.Age = 17;
person.Serialize ("C:\", "person.xml");

// Read the class from a xml file
// Lese die Klasse aus einer XML datei
Person person = XMLSerializer.Deserialize<Person>("C:\person.xml");
using System;
using System.IO;

namespace Splitporn
{
	public static class XMLSerializer
	{
		public static void Serialize<T> (this T baseType, string path, string filename)
		{
			System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer (typeof (T));

			if (!Directory.Exists (path)) {
				string ShortDirectory = (path.Length > 30) ? (path.Substring (0, 30) + "...") : (path);
				throw new DirectoryNotFoundException (string.Format ("Directory \"{0}\" not found", ShortDirectory));
			}

			using (FileStream stream = new FileStream (Path.Combine (path, filename), FileMode.Create, FileAccess.Write, FileShare.Read))
			{
				serializer.Serialize (stream, baseType);
			}
		}

		public static T Deserialize <T> (string filename)
		{
			System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer (typeof(T));

			if (!File.Exists (filename))
			{
				string ShortDirectory = (filename.Length > 30) ? (filename.Substring (0, 30) + "...") : (filename);
				throw new FileNotFoundException (string.Format ("Directory \"{0}\" not found", ShortDirectory));
			}

			T theclass;

			using (FileStream stream = new FileStream (filename, FileMode.Open, FileAccess.Read, FileShare.Read))
			{
				theclass = (T)serializer.Deserialize (stream);
			}

			return theclass;
		}
	}
}

Kommentare zum Snippet

 

Logge dich ein, um hier zu kommentieren!