/// <summary>
/// xml工具类
/// </summary>
public class XmlHelper
{
/// <summary>
/// 序列化xml
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string XmlSerialize<T>(T obj)
{
try
{
using (StringWriter sw = new StringWriter())
{
Type t = obj.GetType();
XmlSerializer serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(sw, obj);
sw.Close();
return sw.ToString();
}
}
catch (Exception ex)
{
WriteTxt("实体序列化xml失败:" + ex);
return string.Empty;
}
}
/// <summary>
/// 序列化xml到文件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static void XmlSerialize<T>(T obj, string path)
{
try
{
string xml = string.Empty;
using (StringWriter sw = new StringWriter())
{
Type t = obj.GetType();
XmlSerializer serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(sw, obj);
sw.Close();
xml = sw.ToString();
}
if (string.IsNullOrWhiteSpace(xml))
{
WriteTxt("实体序列化xml为空");
return;
}
FileHelper.WriteFile(FileHelper.CreateFileAbsolutePath(path, true), xml);
}
catch (Exception ex)
{
WriteTxt("实体序列化xml文件失败:" + ex);
}
}
/// <summary>
/// 反序列化xml
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="strXML"></param>
/// <returns></returns>
public static T DESerializer<T>(string strXML) where T : class
{
try
{
using (StringReader sr = new StringReader(strXML))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return serializer.Deserialize(sr) as T;
}
}
catch (Exception ex)
{
WriteTxt("xml反序列化实体失败[" + ex);
return null;
}
}
/// <summary>
/// 读取xml文件,反序列化实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="path"></param>
/// <returns></returns>
//public static T DESerializerByFile<T>(string path) where T : class
//{
// try
// {
// if (!FileHelper.FileExistByPath(path))
// {
// WriteTxt(string.Format("文件{0}不存在", path));
// return null;
// }
// string strXML = FileHelper.ReadFileToStr(path);
// using (StringReader sr = new StringReader(strXML))
// {
// XmlSerializer serializer = new XmlSerializer(typeof(T));
// return serializer.Deserialize(sr) as T;
// }
// }
// catch (Exception ex)
// {
// WriteTxt("xml反序列化实体失败:" + ex);
// return null;
// }
//}
/// <summary>
/// 清除xml中指定内容
/// </summary>
/// <param name="xml"></param>
/// <param name="cleraStr"></param>
/// <returns></returns>
public static string Clear(string xml, string cleraStr)
{
try
{
string xml_clear = xml.Replace(cleraStr, string.Empty);
return xml_clear;
}
catch (Exception ex)
{
WriteTxt("清除xml中指定内容失败:" + ex);
return xml;
}
}
/// <summary>
/// 清除xml中指定内容
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
public static string Clear(string xml, List<string> clearList)
{
string xml_result = xml;
try
{
if (clearList != null)
{
foreach (string clearItem in clearList)
{
xml_result = xml.Replace(clearItem.Trim(), string.Empty);
xml = xml_result;
}
}
}
catch (Exception ex)
{
}
return xml_result;
}
/// <summary>
/// 格式化xml
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
public static string Format(string xml)
{
string resultXml = xml;
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
System.IO.StringWriter sw = new System.IO.StringWriter();
using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(sw))
{
writer.Indentation = 2; // the Indentation
writer.Formatting = System.Xml.Formatting.Indented;
doc.WriteContentTo(writer);
writer.Close();
}
resultXml = sw.ToString();
}
catch (Exception ex)
{
WriteTxt("格式化xmlm出错:" + ex);
}
return resultXml;
}
/// <summary>
/// 解析XML,匹配替换模板中的内容
/// </summary>
/// <param name="content">模板内容</param>
/// <param name="obj">模板对应的对象</param>
/// <param name="GetType">模板对应的对象的类的类型</param>
/// <returns></returns>
public static string ParseXML(string content, object obj, Type GetType)
{
//结束贪婪模式
Regex r = new Regex(@"\{(\w+?)\}");
MatchCollection matches = r.Matches(content);
foreach (Match matche in matches)
{
#region 匹配替换
//提取组
Group g = matche.Groups[1];
//属性名
string key = g.Value;
//属性
var property = GetType.GetProperty(key);
//属性里面的值
string value = "";
if (property != null)
{
object proobj = property.GetValue(obj, null);
if (proobj != null)
{
value = proobj.ToString();
}
}
else
{
string nullstr = "";
}
Regex r1 = new Regex(@"\{" + key + @"\}");
content = r1.Replace(content, value);
#endregion
}
return content;
}
/// <summary>
/// 写日志(日志文件位置与主程序exe位置相同)
/// </summary>
/// <param name="strText">日志内容</param>
/// <param name="strFileName">日志文件名称</param>
private static void WriteTxt(string strText, string strFileName = null)
{
try
{
if (strFileName == null || strFileName.Trim() == string.Empty)
{
strFileName = "Log.txt";
}
string strFilePath = AppDomain.CurrentDomain.BaseDirectory + strFileName;
System.IO.StreamWriter sw = new System.IO.StreamWriter(strFilePath, true, System.Text.Encoding.Default);
sw.WriteLine(strText);
sw.Close();
}
catch (Exception)
{ }
}
}
/// <summary>
/// 文件操作类
/// </summary>
public class FileHelper
{
[DllImport("kernel32.dll")]
public static extern IntPtr _lopen(string lpPathName, int iReadWrite);
[DllImport("kernel32.dll")]
public static extern bool CloseHandle(IntPtr hObject);
public const int OF_READWRITE = 2;
public const int OF_SHARE_DENY_NONE = 0x40;
public static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
/// <summary>
/// 根据路径判断文件是否存在
/// </summary>
/// <param name="path"></param>
/// <returns>true表示存在,false不存在</returns>
public static bool FileExistByPath(string path)
{
bool result = false;
try
{
if (path.Contains(":"))
{
if (File.Exists(path))
result = true;
}
else
{
string absolutePath = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, path);
if (File.Exists(absolutePath))
result = true;
}
}
catch (Exception ex)
{
if (path.Contains(":"))
{
WriteTxt(string.Format("绝对路径判断文件是否存在出错,绝对路径{0}", path) + ex.Message);
}
else
{
WriteTxt(string.Format("相对路径判断文件是否存在出错,根路径{0},相对路径{1}", AppDomain.CurrentDomain.BaseDirectory, path)+ex.Message);
}
}
return result;
}
/// <summary>
/// 创建文件绝对路径
/// </summary>
/// <param name="path"></param>
/// <param name="isRelativePath"></param>
/// <returns></returns>
public static string CreateFileAbsolutePath(string path, bool isRelativePath)
{
string absolutePath = path;
try
{
if (isRelativePath && !path.Contains(":"))
absolutePath = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, path);
}
catch (Exception ex)
{
WriteTxt("【" + ex.Message + "】");
}
return absolutePath;
}
/// <summary>
/// 根据文件路径判断文件是否被占用
/// </summary>
/// <param name="path"></param>
/// <returns>true表示正在使用,false没有使用</returns>
public static bool FileOccupy(string path)
{
bool inUse = true;
try
{
if (!FileExistByPath(path))
{
WriteTxt("文件都不存在" );
inUse = false;
return inUse;
}
IntPtr vHandle = _lopen(path, OF_READWRITE | OF_SHARE_DENY_NONE);
if (vHandle == HFILE_ERROR)
{
WriteTxt("文件被占用");
return inUse;
}
CloseHandle(vHandle);
inUse = false;
}
catch (Exception ex)
{
WriteTxt("判断文件是否被占用失败【" + ex.Message + "】");
}
return inUse;
}
/// <summary>
/// 根据文件路径判断文件是否被占用
/// </summary>
/// <param name="fileName"></param>
/// <returns>true表示正在使用,false没有使用</returns>
public static bool IsFileInUse(string path)
{
bool inUse = true;
FileStream fs = null;
try
{
if (!FileExistByPath(path))
{
WriteTxt("文件都不存在!");
inUse = false;
return inUse;
}
fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None);
inUse = false;
}
catch (Exception ex)
{
WriteTxt("判断文件是否被占用失败" + ex.Message);
}
finally
{
if (fs != null)
fs.Close();
}
return inUse;
}
/// <summary>
/// 根据文件路径读取string
/// </summary>
/// <param name="path"></param>
/// <returns>true表示正在使用,false没有使用</returns>
public static string ReadFile2Str(string path)
{
string resultStr = string.Empty;
try
{
//打开文件时总写日志,先注释掉
//int i = 0;
//int waitTime = 3000;
//int interval = 100;
//while (i <= waitTime)
//{
// if (!IsFileInUse(path))
// break;
// Thread.Sleep(interval);
// i += interval;
//}
resultStr = File.ReadAllText(path);
}
catch (Exception ex)
{
WriteTxt("读取文件失败" + ex.Message);
}
return resultStr;
}
/// <summary>
/// 保存字符串到文件
/// </summary>
/// <param name="absolutePath"></param>
/// <param name="contents"></param>
public static void WriteFile(string absolutePath, string contents)
{
try
{
string rootPath = Path.GetDirectoryName(absolutePath);
if (!Directory.Exists(rootPath))
{
DirectoryInfo dirc = Directory.CreateDirectory(rootPath);
}
File.WriteAllText(absolutePath, contents);
}
catch (Exception ex)
{
WriteTxt("写文件失败" + ex.Message);
}
}
/// <summary>
/// 保存xml
/// </summary>
/// <param name="xml"></param>
/// <param name="path"></param>
public static void SaveXml(string xml, string path)
{
try
{
DateTime dt = DateTime.Now;
//保存xml
FileHelper.WriteFile(FileHelper.CreateFileAbsolutePath(string.Format("{0}\\{1}\\{2}\\{3}.txt", path, dt.ToString("yyyyMMdd"), dt.ToString("HH"), dt.ToString("yyyyMMddHHmmss")), true), xml);
}
catch (Exception ex)
{
WriteTxt("保存xml失败" + ex.Message);
}
}
private static void WriteTxt(string strText, string strFileName = null)
{
try
{
if (strFileName == null || strFileName.Trim() == string.Empty)
{
strFileName = "Log.txt";
}
string strFilePath = AppDomain.CurrentDomain.BaseDirectory + strFileName;
System.IO.StreamWriter sw = new System.IO.StreamWriter(strFilePath, true, System.Text.Encoding.Default);
sw.WriteLine(strText);
sw.Close();
}
catch (Exception)
{ }
}
}