91 lines
3.2 KiB
C#
91 lines
3.2 KiB
C#
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using System.Runtime.Serialization;
|
|
using System.Runtime.Serialization.Formatters.Binary;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.Xml;
|
|
using System.Xml.Serialization;
|
|
|
|
namespace Ewide.Core.Util
|
|
{
|
|
public class XmlSerializerUtil
|
|
{
|
|
static string[] str = AppDomain.CurrentDomain.BaseDirectory.Split("ewide_core");
|
|
static string path = str[0]+ @"ewide_core\Api\Ewide.Core\SeedDataXml\";
|
|
public Dictionary<Type, object> ReaderALL()
|
|
{
|
|
Dictionary<Type, object> dic = new Dictionary<Type, object>();
|
|
DirectoryInfo folder = new DirectoryInfo(path);
|
|
foreach (FileInfo file in folder.GetFiles())
|
|
{
|
|
//除去.xml 后缀
|
|
string className = file.Name.Remove(file.Name.Length - 4, 4);
|
|
object obj = AppInfo(className);
|
|
string XmlContext = StreamRead(file.FullName);
|
|
//实例创建 出 类型集合
|
|
var modelList = Activator.CreateInstance(typeof(List<>).MakeGenericType(new Type[] { obj.GetType() }));
|
|
var list = Deserialize(modelList.GetType(), XmlContext);
|
|
dic.Add(obj.GetType(), list);
|
|
}
|
|
return dic;
|
|
}
|
|
private object Deserialize<T>(string xmlContent, Type[] Arrtype)
|
|
{
|
|
object obj = null;
|
|
using (StringReader sr = new StringReader(xmlContent))
|
|
{
|
|
XmlSerializer xmldes = new XmlSerializer(typeof(List<T>), Arrtype);
|
|
obj = xmldes.Deserialize(sr);
|
|
}
|
|
return obj;
|
|
}
|
|
private object Deserialize(Type type, string xmlContent)
|
|
{
|
|
object obj = null;
|
|
using (StringReader sr = new StringReader(xmlContent))
|
|
{
|
|
XmlSerializer xmldes = new XmlSerializer(type);
|
|
obj = xmldes.Deserialize(sr);
|
|
}
|
|
return obj;
|
|
}
|
|
public string StreamRead(string path)
|
|
{
|
|
using (StreamReader reader = new StreamReader(path, Encoding.Default))
|
|
{
|
|
return reader.ReadToEnd();
|
|
}
|
|
}
|
|
private object AppInfo(string name)
|
|
{
|
|
string assemblyName = "Ewide.Core";
|
|
string nameSpace = "Ewide.Core";
|
|
string fullName = nameSpace + "." + name;
|
|
object ect = Assembly.Load(assemblyName).CreateInstance(fullName);
|
|
return ect;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 写入XML到磁盘
|
|
/// </summary>
|
|
/// <param name="type">类型</param>
|
|
/// <param name="data">数据</param>
|
|
/// <param name="className">XML名称</param>
|
|
public void WriteXML(Type type, object data, string className)
|
|
{
|
|
|
|
string writePath = path + className + ".xml";
|
|
using (FileStream fs = new FileStream(writePath, FileMode.OpenOrCreate))
|
|
{
|
|
XmlSerializer ser = new XmlSerializer(type);
|
|
ser.Serialize(fs, data);
|
|
}
|
|
}
|
|
}
|
|
}
|