/*
* Copyright (C) 2004-2005 Jonathan Bindel
* Copyright (C) 2007 Eskil Bylund
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
using System;
using System.Diagnostics;
using System.IO;
using System.Xml.Serialization;
namespace DCSharp.Xml{
public class XmlHelper
{
public static void Serialize(object instance, string path)
{
Type type = instance.GetType();
XmlSerializer xs = new XmlSerializer(type);
Directory.CreateDirectory(Path.GetDirectoryName(path));
using (FileStream fs = File.Open(path, FileMode.Create,
FileAccess.Write, FileShare.Read))
{
xs.Serialize(fs, instance);
}
}
public static object Deserialize(Type type, string path)
{
XmlSerializer xs = null;
try
{
xs = new XmlSerializer(type);
using (FileStream fs = File.Open(path, FileMode.Open,
FileAccess.Read))
{
return xs.Deserialize(fs);
}
}
catch (DirectoryNotFoundException)
{
}
catch (FileNotFoundException)
{
}
catch (Exception ex)
{
DumpException(ex);
}
return Activator.CreateInstance(type);
}
private static void DumpException(Exception ex)
{
WriteExceptionInfo(ex);
while (ex.InnerException != null)
{
WriteExceptionInfo(ex.InnerException);
ex = ex.InnerException;
}
}
private static void WriteExceptionInfo(Exception ex)
{
Debug.WriteLine("--------- Exception Data ---------");
Debug.WriteLine("Message: " + ex.Message);
Debug.WriteLine("Exception Type: " + ex.GetType().FullName);
Debug.WriteLine("Source: " + ex.Source);
Debug.WriteLine("StrackTrace: " + ex.StackTrace);
Debug.WriteLine("TargetSite: " + ex.TargetSite);
}
}
}
|