1、引入命名空间 system.xml.dll
2、序列化反序列化xml辅助类代码
using System.Xml.Serialization;
/// <summary>
/// XMLSerialiaze 默认帮助/// </summary>
/// <typeparam name="T">xml序列化和反序列化的类型</typeparam>
public class XMLSerialiazeHelper<T>
{
/// <summary>
/// 序列化
/// </summary>
/// <param name="classInstace">xml序列化的类实例</param>
/// <param name="filePath">类所在的路径</param>
public static void Serialiaze(T classInstace, string filePath)
{
string appPath = filePath;
XmlSerializer xmlSeial = new XmlSerializer(typeof(T));
if (File.Exists(appPath))
{
File.Delete(appPath);
}
using (FileStream fsXml = File.Create(appPath))
{
xmlSeial.Serialize(fsXml, classInstace);
fsXml.Close();
}
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="filePath">反序列化类所在xml文件路径</param>
/// <returns>类型</returns>
public static T Deserialize(string filePath)
{
string appPath = filePath;
T classInstace;
XmlSerializer xmlSeial = new XmlSerializer(typeof(T));
if (File.Exists(appPath))
{
using (FileStream fsXml = File.Open(appPath, FileMode.Open, FileAccess.ReadWrite))
{
try
{
classInstace = (T)xmlSeial.Deserialize(fsXml);
}
catch (Exception ex)
{
return default(T);
}
fsXml.Close();
}
}
else
{
File.Create(filePath);
throw new FileNotFoundException("没有找到文件-" + filePath);
}
return classInstace;
}
}
3、创建配置类
/// <summary>
/// 评估配置
/// </summary>
[XmlRoot(ElementName = "配置根节点")]
public class AssessConfig
{
[XmlArray(ElementName = "列名")]
public string[] Columns
{
get;
set;
}
}
4、初始化配置文件类
/// <summary>
/// 全局初始化
/// </summary>
public static void InitGlobal()
{
string path = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, CONFIGNAME);
if (!File.Exists(path))
{
cfg = new AssessConfig()
{
Columns = new string[]
{
"name",
"address"
}
};
Serialiaze(cfg, path);
}
else
{
Deserialize(path);
}
}