我是靠谱客的博主 暴躁花生,最近开发中收集的这篇文章主要介绍xml 封装类,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

 

 

public static class XmlHelper
{
public static T FromXmlFile<T>(this string filePath) where T : new()
{
T result = new T();
if (!File.Exists(filePath))
{
return result;
}
try
{
using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read))
{
fileStream.Position = 0L;
result = (T)new XmlSerializer(typeof(T)).Deserialize(fileStream);
fileStream.Close();
return result;
}
}
catch (Exception ex)
{
throw ex;
}
}
public static void ToXmlFile(this object data, string filePath, Encoding encode = null)
{
if (encode == null)
{
encode = Encoding.UTF8;
}
string s = data.ToXmlString(encode);
encode.GetBytes(s).BytesToFile(filePath);
}
public static string ToXmlString(this object data)
{
return data.ToXmlString(Encoding.UTF8);
}
public static string ToXmlString(this object data, Encoding encode)
{
if (encode == null)
{
return Encoding.Default.GetString(data.ToXmlByte());
}
return encode.GetString(data.ToXmlByte());
}
public static byte[] ToXmlByte(this object data)
{
byte[] array = new byte[0];
try
{
using (MemoryStream memoryStream = new MemoryStream())
{
new XmlSerializer(data.GetType()).Serialize(memoryStream, data);
array = memoryStream.ToArray();
memoryStream.Flush();
return array;
}
}
catch (Exception ex)
{
throw ex;
}
}
public static T FromXmlString<T>(this string XmlString)
{
if (string.IsNullOrEmpty(XmlString))
{
return default(T);
}
return Encoding.UTF8.GetBytes(XmlString).FromXmlByte<T>(Encoding.UTF8);
}
public static T FromXmlString<T>(this string XmlString, Encoding encode)
{
if (string.IsNullOrEmpty(XmlString))
{
return default(T);
}
return encode.GetBytes(XmlString).FromXmlByte<T>(encode);
}
public static T FromXmlByte<T>(this byte[] buffer, Encoding encode)
{
try
{
using (MemoryStream memoryStream = new MemoryStream(buffer))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
new XmlTextWriter(memoryStream, encode);
object obj = xmlSerializer.Deserialize(memoryStream);
if (obj == null)
{
return default(T);
}
return (T)obj;
}
}
catch (Exception ex)
{
throw ex;
}
}
public static void BytesToFile(this byte[] byts, string filename)
{
if (!string.IsNullOrEmpty(filename))
{
FileInfo fileInfo = new FileInfo(filename);
if (!Directory.Exists(fileInfo.DirectoryName))
{
Directory.CreateDirectory(fileInfo.DirectoryName);
}
using (FileStream output = new FileStream(filename, FileMode.Create))
{
using (BinaryWriter binaryWriter = new BinaryWriter(output))
{
binaryWriter.Write(byts);
}
}
}
}
}

 

转载于:https://www.cnblogs.com/nocanstillbb/p/10482262.html

最后

以上就是暴躁花生为你收集整理的xml 封装类的全部内容,希望文章能够帮你解决xml 封装类所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(47)

评论列表共有 0 条评论

立即
投稿
返回
顶部