转移.net core 3.1,为.NET 5做准备

This commit is contained in:
ÂëÉñ
2020-10-22 14:59:36 +08:00
parent fd9bca23a7
commit a35d596237
1080 changed files with 175912 additions and 185681 deletions

View File

@@ -0,0 +1,122 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace Infrastructure.Helpers
{
/// <summary>
/// 常用公共类
/// </summary>
public class CommonHelper
{
#region Stopwatch计时器
/// <summary>
/// 计时器开始
/// </summary>
/// <returns></returns>
public static Stopwatch TimerStart()
{
Stopwatch watch = new Stopwatch();
watch.Reset();
watch.Start();
return watch;
}
/// <summary>
/// 计时器结束
/// </summary>
/// <param name="watch"></param>
/// <returns></returns>
public static string TimerEnd(Stopwatch watch)
{
watch.Stop();
double costtime = watch.ElapsedMilliseconds;
return costtime.ToString();
}
#endregion
#region
/// <summary>
/// 删除数组中的重复项
/// </summary>
/// <param name="values"></param>
/// <returns></returns>
public static string[] RemoveDup(string[] values)
{
List<string> list = new List<string>();
for (int i = 0; i < values.Length; i++)//遍历数组成员
{
if (!list.Contains(values[i]))
{
list.Add(values[i]);
};
}
return list.ToArray();
}
#endregion
#region
/// <summary>
/// 自动生成编号 201008251145409865
/// </summary>
/// <returns></returns>
public static string CreateNo()
{
Random random = new Random();
string strRandom = random.Next(1000, 10000).ToString(); //生成编号
string code = DateTime.Now.ToString("yyyyMMddHHmmss") + strRandom;//形如
return code;
}
#endregion
#region 0-9
/// <summary>
/// 生成0-9随机数
/// </summary>
/// <param name="codeNum">生成长度</param>
/// <returns></returns>
public static string RndNum(int codeNum)
{
StringBuilder sb = new StringBuilder(codeNum);
Random rand = new Random();
for (int i = 1; i < codeNum + 1; i++)
{
int t = rand.Next(9);
sb.AppendFormat("{0}", t);
}
return sb.ToString();
}
#endregion
#region
/// <summary>
/// 删除最后结尾的一个逗号
/// </summary>
public static string DelLastComma(string str)
{
return str.Substring(0, str.LastIndexOf(","));
}
/// <summary>
/// 删除最后结尾的指定字符后的字符
/// </summary>
public static string DelLastChar(string str, string strchar)
{
return str.Substring(0, str.LastIndexOf(strchar));
}
/// <summary>
/// 删除最后结尾的长度
/// </summary>
/// <param name="str"></param>
/// <param name="Length"></param>
/// <returns></returns>
public static string DelLastLength(string str, int Length)
{
if (string.IsNullOrEmpty(str))
return "";
str = str.Substring(0, str.Length - Length);
return str;
}
#endregion
}
}

View File

@@ -0,0 +1,42 @@
using System;
namespace Infrastructure.Helpers
{
public class DateTimeHelper
{
public static string FriendlyDate(DateTime? date)
{
if (!date.HasValue) return string.Empty;
string strDate = date.Value.ToString("yyyy-MM-dd");
string vDate = string.Empty;
if(DateTime.Now.ToString("yyyy-MM-dd")==strDate)
{
vDate = "今天";
}
else if (DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") == strDate)
{
vDate = "明天";
}
else if (DateTime.Now.AddDays(2).ToString("yyyy-MM-dd") == strDate)
{
vDate = "后天";
}
else if (DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") == strDate)
{
vDate = "昨天";
}
else if (DateTime.Now.AddDays(2).ToString("yyyy-MM-dd") == strDate)
{
vDate = "前天";
}
else
{
vDate = strDate;
}
return vDate;
}
}
}

View File

@@ -0,0 +1,339 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Infrastructure.Extensions;
namespace Infrastructure.Helpers
{
public class FileHelper
{
private static object _filePathObj = new object();
/// <summary>
/// 通过迭代器读取平面文件行内容(必须是带有\r\n换行的文件,百万行以上的内容读取效率存在问题,适用于100M左右文件行100W内超出的会有卡顿)
/// </summary>
/// <param name="fullPath">文件全路径</param>
/// <param name="page">分页页数</param>
/// <param name="pageSize">分页大小</param>
/// <param name="seekEnd"> 是否最后一行向前读取,默认从前向后读取</param>
/// <returns></returns>
public static IEnumerable<string> ReadPageLine(string fullPath, int page, int pageSize, bool seekEnd = false)
{
if (page <= 0)
{
page = 1;
}
fullPath = StringExtension.ReplacePath(fullPath);
var lines = File.ReadLines(fullPath, Encoding.UTF8);
if (seekEnd)
{
int lineCount = lines.Count();
int linPageCount = (int)Math.Ceiling(lineCount / (pageSize * 1.00));
//超过总页数,不处理
if (page > linPageCount)
{
page = 0;
pageSize = 0;
}
else if (page == linPageCount)//最后一页,取最后一页剩下所有的行
{
pageSize = lineCount - (page - 1) * pageSize;
if (page == 1)
{
page = 0;
}
else
{
page = lines.Count() - page * pageSize;
}
}
else
{
page = lines.Count() - page * pageSize;
}
}
else
{
page = (page - 1) * pageSize;
}
lines = lines.Skip(page).Take(pageSize);
var enumerator = lines.GetEnumerator();
int count = 1;
while (enumerator.MoveNext() || count <= pageSize)
{
yield return enumerator.Current;
count++;
}
enumerator.Dispose();
}
public static bool FileExists(string path)
{
return File.Exists(StringExtension.ReplacePath(path));
}
public static string GetCurrentDownLoadPath()
{
return ("Download\\").MapPath();
}
public static bool DirectoryExists(string path)
{
return Directory.Exists(StringExtension.ReplacePath(path));
}
public static string Read_File(string fullpath, string filename, string suffix)
{
return ReadFile((fullpath + "\\" + filename + suffix).MapPath());
}
public static string ReadFile(string fullName)
{
// Encoding code = Encoding.GetEncoding(); //Encoding.GetEncoding("gb2312");
string temp = fullName.MapPath().ReplacePath();
string str = "";
if (!File.Exists(temp))
{
return str;
}
StreamReader sr = null;
try
{
sr = new StreamReader(temp);
str = sr.ReadToEnd(); // 读取文件
}
catch { }
sr?.Close();
sr?.Dispose();
return str;
}
/// <summary>
/// 取后缀名
/// </summary>
/// <param name="filename">文件名</param>
/// <returns>.gif|.html格式</returns>
public static string GetPostfixStr(string filename)
{
int start = filename.LastIndexOf(".");
int length = filename.Length;
string postfix = filename.Substring(start, length - start);
return postfix;
}
/// <summary>
///
/// </summary>
/// <param name="path">路径 </param>
/// <param name="fileName">文件名</param>
/// <param name="content">写入的内容</param>
/// <param name="appendToLast">是否将内容添加到未尾,默认不添加</param>
public static void WriteFile(string path, string fileName, string content, bool appendToLast = false)
{
path = StringExtension.ReplacePath(path);
fileName = StringExtension.ReplacePath(fileName);
if (!Directory.Exists(path))//如果不存在就创建file文件夹
Directory.CreateDirectory(path);
using (FileStream stream = File.Open(Path.Combine(path, fileName), FileMode.OpenOrCreate, FileAccess.Write))
{
byte[] by = Encoding.Default.GetBytes(content);
if (appendToLast)
{
stream.Position = stream.Length;
}
else
{
stream.SetLength(0);
}
stream.Write(by, 0, by.Length);
}
}
/// <summary>
/// 追加文件
/// </summary>
/// <param name="Path">文件路径</param>
/// <param name="strings">内容</param>
public static void FileAdd(string Path, string strings)
{
StreamWriter sw = File.AppendText(StringExtension.ReplacePath(Path));
sw.Write(strings);
sw.Flush();
sw.Close();
sw.Dispose();
}
/// <summary>
/// 拷贝文件
/// </summary>
/// <param name="OrignFile">原始文件</param>
/// <param name="NewFile">新文件路径</param>
public static void FileCoppy(string OrignFile, string NewFile)
{
File.Copy(StringExtension.ReplacePath(OrignFile), StringExtension.ReplacePath(NewFile), true);
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="Path">路径</param>
public static void FileDel(string Path)
{
File.Delete(StringExtension.ReplacePath(Path));
}
/// <summary>
/// 移动文件
/// </summary>
/// <param name="OrignFile">原始路径</param>
/// <param name="NewFile">新路径</param>
public static void FileMove(string OrignFile, string NewFile)
{
File.Move(StringExtension.ReplacePath(OrignFile), StringExtension.ReplacePath(NewFile));
}
/// <summary>
/// 在当前目录下创建目录
/// </summary>
/// <param name="OrignFolder">当前目录</param>
/// <param name="NewFloder">新目录</param>
public static void FolderCreate(string OrignFolder, string NewFloder)
{
Directory.SetCurrentDirectory(StringExtension.ReplacePath(OrignFolder));
Directory.CreateDirectory(StringExtension.ReplacePath(NewFloder));
}
/// <summary>
/// 创建文件夹
/// </summary>
/// <param name="Path"></param>
public static void FolderCreate(string Path)
{
// 判断目标目录是否存在如果不存在则新建之
if (!Directory.Exists(StringExtension.ReplacePath(Path)))
Directory.CreateDirectory(StringExtension.ReplacePath(Path));
}
public static void FileCreate(string Path)
{
FileInfo CreateFile = new FileInfo(StringExtension.ReplacePath(Path)); //创建文件
if (!CreateFile.Exists)
{
FileStream FS = CreateFile.Create();
FS.Close();
}
}
/// <summary>
/// 递归删除文件夹目录及文件
/// </summary>
/// <param name="dir"></param>
/// <returns></returns>
public static void DeleteFolder(string dir)
{
dir = StringExtension.ReplacePath(dir);
if (Directory.Exists(dir)) //如果存在这个文件夹删除之
{
foreach (string d in Directory.GetFileSystemEntries(dir))
{
if (File.Exists(d))
File.Delete(d); //直接删除其中的文件
else
DeleteFolder(d); //递归删除子文件夹
}
Directory.Delete(dir, true); //删除已空文件夹
}
}
/// <summary>
/// 指定文件夹下面的所有内容copy到目标文件夹下面
/// </summary>
/// <param name="srcPath">原始路径</param>
/// <param name="aimPath">目标文件夹</param>
public static void CopyDir(string srcPath, string aimPath)
{
try
{
aimPath = StringExtension.ReplacePath(aimPath);
// 检查目标目录是否以目录分割字符结束如果不是则添加之
if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
aimPath += Path.DirectorySeparatorChar;
// 判断目标目录是否存在如果不存在则新建之
if (!Directory.Exists(aimPath))
Directory.CreateDirectory(aimPath);
// 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
//如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
//string[] fileList = Directory.GetFiles(srcPath);
string[] fileList = Directory.GetFileSystemEntries(StringExtension.ReplacePath(srcPath));
//遍历所有的文件和目录
foreach (string file in fileList)
{
//先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
if (Directory.Exists(file))
CopyDir(file, aimPath + Path.GetFileName(file));
//否则直接Copy文件
else
File.Copy(file, aimPath + Path.GetFileName(file), true);
}
}
catch (Exception ee)
{
throw new Exception(ee.ToString());
}
}
/// <summary>
/// 获取文件夹大小
/// </summary>
/// <param name="dirPath">文件夹路径</param>
/// <returns></returns>
public static long GetDirectoryLength(string dirPath)
{
dirPath = StringExtension.ReplacePath(dirPath);
if (!Directory.Exists(dirPath))
return 0;
long len = 0;
DirectoryInfo di = new DirectoryInfo(dirPath);
foreach (FileInfo fi in di.GetFiles())
{
len += fi.Length;
}
DirectoryInfo[] dis = di.GetDirectories();
if (dis.Length > 0)
{
for (int i = 0; i < dis.Length; i++)
{
len += GetDirectoryLength(dis[i].FullName);
}
}
return len;
}
/// <summary>
/// 获取指定文件详细属性
/// </summary>
/// <param name="filePath">文件详细路径</param>
/// <returns></returns>
public static string GetFileAttibe(string filePath)
{
string str = "";
filePath = StringExtension.ReplacePath(filePath);
System.IO.FileInfo objFI = new System.IO.FileInfo(filePath);
str += "详细路径:" + objFI.FullName + "<br>文件名称:" + objFI.Name + "<br>文件长度:" + objFI.Length.ToString() + "字节<br>创建时间" + objFI.CreationTime.ToString() + "<br>最后访问时间:" + objFI.LastAccessTime.ToString() + "<br>修改时间:" + objFI.LastWriteTime.ToString() + "<br>所在目录:" + objFI.DirectoryName + "<br>扩展名:" + objFI.Extension;
return str;
}
}
}

View File

@@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace Infrastructure.Helpers
{
/// <summary>
/// List转成Tree
/// <para>李玉宝新增于2016-10-09 19:54:07</para>
/// </summary>
public static class GenericHelpers
{
/// <summary>
/// Generates tree of items from item list
/// </summary>
///
/// <typeparam name="T">Type of item in collection</typeparam>
/// <typeparam name="K">Type of parent_id</typeparam>
///
/// <param name="collection">Collection of items</param>
/// <param name="idSelector">Function extracting item's id</param>
/// <param name="parentIdSelector">Function extracting item's parent_id</param>
/// <param name="rootId">Root element id</param>
///
/// <returns>Tree of items</returns>
public static IEnumerable<TreeItem<T>> GenerateTree<T, K>(
this IEnumerable<T> collection,
Func<T, K> idSelector,
Func<T, K> parentIdSelector,
K rootId = default(K))
{
foreach (var c in collection.Where(u =>
{
var selector = parentIdSelector(u);
return (rootId == null && selector == null)
|| (rootId != null &&rootId.Equals(selector));
}))
{
yield return new TreeItem<T>
{
Item = c,
Children = collection.GenerateTree(idSelector, parentIdSelector, idSelector(c))
};
}
}
/// <summary>
/// 把数组转为逗号连接的字符串
/// </summary>
/// <param name="data"></param>
/// <param name="Str"></param>
/// <returns></returns>
public static string ArrayToString(dynamic data, string Str)
{
string resStr = Str;
foreach (var item in data)
{
if (resStr != "")
{
resStr += ",";
}
if (item is string)
{
resStr += item;
}
else
{
resStr += item.Value;
}
}
return resStr;
}
}
}

View File

@@ -0,0 +1,175 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
namespace Infrastructure.Helpers
{
/// <summary>
/// http请求类
/// </summary>
public class HttpHelper
{
private HttpClient _httpClient;
private string _baseIPAddress;
/// <param name="ipaddress">请求的基础IP例如http://192.168.0.33:8080/ </param>
public HttpHelper(string ipaddress = "")
{
this._baseIPAddress = ipaddress;
_httpClient = new HttpClient { BaseAddress = new Uri(_baseIPAddress) };
}
/// <summary>
/// 创建带用户信息的请求客户端
/// </summary>
/// <param name="userName">用户账号</param>
/// <param name="pwd">用户密码当WebApi端不要求密码验证时可传空串</param>
/// <param name="uriString">The URI string.</param>
public HttpHelper(string userName, string pwd = "", string uriString = "")
: this(uriString)
{
if (!string.IsNullOrEmpty(userName))
{
_httpClient.DefaultRequestHeaders.Authorization = CreateBasicCredentials(userName, pwd);
}
}
/// <summary>
/// Get请求数据
/// /// <para>最终以url参数的方式提交</para>
/// <para>yubaolee 2016-3-3 重构与post同样异步调用</para>
/// </summary>
/// <param name="parameters">参数字典,可为空</param>
/// <param name="requestUri">例如/api/Files/UploadFile</param>
/// <returns></returns>
public string Get(Dictionary<string, string> parameters, string requestUri)
{
if (parameters != null)
{
var strParam = string.Join("&", parameters.Select(o => o.Key + "=" + o.Value));
requestUri = string.Concat(ConcatURL(requestUri), '?', strParam);
}
else
{
requestUri = ConcatURL(requestUri);
}
var result = _httpClient.GetStringAsync(requestUri);
return result.Result;
}
/// <summary>
/// Get请求数据
/// <para>最终以url参数的方式提交</para>
/// </summary>
/// <param name="parameters">参数字典</param>
/// <param name="requestUri">例如/api/Files/UploadFile</param>
/// <returns>实体对象</returns>
public T Get<T>(Dictionary<string, string> parameters, string requestUri) where T : class
{
string jsonString = Get(parameters, requestUri);
if (string.IsNullOrEmpty(jsonString))
return null;
return JsonHelper.Instance.Deserialize<T>(jsonString);
}
/// <summary>
/// 以json的方式Post数据 返回string类型
/// <para>最终以json的方式放置在http体中</para>
/// </summary>
/// <param name="entity">实体</param>
/// <param name="requestUri">例如/api/Files/UploadFile</param>
/// <returns></returns>
public string Post(object entity, string requestUri)
{
string request = string.Empty;
if (entity != null)
request = JsonHelper.Instance.Serialize(entity);
HttpContent httpContent = new StringContent(request);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return Post(requestUri, httpContent);
}
/// <summary>
/// 提交字典类型的数据
/// <para>最终以formurlencode的方式放置在http体中</para>
/// <para>李玉宝于2016-07-20 19:01:59</para>
/// </summary>
/// <returns>System.String.</returns>
public string PostDicObj(Dictionary<string, object> para, string requestUri)
{
Dictionary<string, string> temp = new Dictionary<string, string>();
foreach (var item in para)
{
if (item.Value != null)
{
if (item.Value.GetType().Name.ToLower() != "string")
{
temp.Add(item.Key, JsonHelper.Instance.Serialize(item.Value));
}
else
{
temp.Add(item.Key, item.Value.ToString());
}
}
else {
temp.Add(item.Key, "");
}
}
return PostDic(temp, requestUri);
}
/// <summary>
/// Post Dic数据
/// <para>最终以formurlencode的方式放置在http体中</para>
/// <para>李玉宝于2016-07-15 15:28:41</para>
/// </summary>
/// <returns>System.String.</returns>
public string PostDic(Dictionary<string, string> temp, string requestUri)
{
HttpContent httpContent = new FormUrlEncodedContent(temp);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
return Post(requestUri, httpContent);
}
public string PostByte(byte[] bytes, string requestUrl)
{
HttpContent content = new ByteArrayContent(bytes);
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return Post(requestUrl, content);
}
private string Post(string requestUrl, HttpContent content)
{
var result = _httpClient.PostAsync(ConcatURL(requestUrl), content);
return result.Result.Content.ReadAsStringAsync().Result;
}
/// <summary>
/// 把请求的URL相对路径组合成绝对路径
/// <para>李玉宝于2016-07-21 9:54:07</para>
/// </summary>
private string ConcatURL(string requestUrl)
{
return new Uri(_httpClient.BaseAddress, requestUrl).OriginalString;
}
private AuthenticationHeaderValue CreateBasicCredentials(string userName, string password)
{
string toEncode = userName + ":" + password;
// The current HTTP specification says characters here are ISO-8859-1.
// However, the draft specification for the next version of HTTP indicates this encoding is infrequently
// used in practice and defines behavior only for ASCII.
Encoding encoding = Encoding.GetEncoding("utf-8");
byte[] toBase64 = encoding.GetBytes(toEncode);
string parameter = Convert.ToBase64String(toBase64);
return new AuthenticationHeaderValue("Basic", parameter);
}
}
}

View File

@@ -0,0 +1,77 @@
// <copyright file="ImgHelper.cs" company="openauth.me">
// Copyright (c) 2019 openauth.me. All rights reserved.
// </copyright>
// <author>www.cnblogs.com/yubaolee</author>
// <date>2019-03-07</date>
// <summary>生成缩略图</summary>
namespace Infrastructure.Helpers
{
public class ImgHelper
{
//MakeThumbnail(path, tpath, 120, 90, "H");
public static void MakeThumbnail(string originalImagePath,
string thumbnailPath,
int width=120, int height=90, string mode="H")
{
//Image originalImage = Image.FromFile(originalImagePath);
//int towidth = width;
//int toheight = height;
//int x = 0;
//int y = 0;
//int ow = originalImage.Width;
//int oh = originalImage.Height;
//switch (mode)
//{
// case "HW"://指定高宽缩放(可能变形)
// break;
// case "W"://指定宽,高按比例
// toheight = originalImage.Height * width / originalImage.Width;
// break;
// case "H"://指定高,宽按比例
// towidth = originalImage.Width * height / originalImage.Height;
// break;
// case "Cut"://指定高宽裁减(不变形)
// if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
// {
// oh = originalImage.Height;
// ow = originalImage.Height * towidth / toheight;
// y = 0;
// x = (originalImage.Width - ow) / 2;
// }
// else
// {
// ow = originalImage.Width;
// oh = originalImage.Width * height / towidth;
// x = 0;
// y = (originalImage.Height - oh) / 2;
// }
// break;
// default:
// break;
//}
//MediaTypeNames.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
//Graphics g = System.Drawing.Graphics.FromImage(bitmap);
//g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//g.Clear(Color.Transparent);
//g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
// new Rectangle(x, y, ow, oh),
// GraphicsUnit.Pixel);
//try
//{
// bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png);
//}
//catch (System.Exception e)
//{
// throw e;
//}
//finally
//{
// originalImage.Dispose();
// bitmap.Dispose();
// g.Dispose();
//}
}
}
}

View File

@@ -0,0 +1,31 @@
using System;
using System.Security.Cryptography;
using System.Text;
namespace Infrastructure.Helpers
{
public class Md5
{
public static string Encrypt(string str)
{
string pwd = String.Empty;
MD5 md5 = MD5.Create();
// 编码UTF8/Unicode 
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
// 转换成字符串
for (int i = 0; i < s.Length; i++)
{
//格式后的字符是小写的字母
//如果使用大写X则格式后的字符是大写字符
pwd = pwd + s[i].ToString("X");
}
return pwd;
}
}
}

View File

@@ -0,0 +1,65 @@
// ***********************************************************************
// Assembly : Infrastructure
// Author : Yubao Li
// Created : 11-23-2015
//
// Last Modified By : Yubao Li
// Last Modified On : 11-23-2015
// ***********************************************************************
// <copyright file="ObjectHelper.cs" company="">
// Copyright (c) . All rights reserved.
// </copyright>
// <summary>
//对象COPY/初始化帮助,通常是防止从视图中传过来的对象属性为空,这其赋初始值
//</summary>
// ***********************************************************************
using System.Reflection;
namespace Infrastructure.Helpers
{
public static class ObjectHelper
{
public static T CopyTo<T>(this object source) where T:class, new()
{
var result = new T();
source.CopyTo(result);
return result;
}
public static void CopyTo<T>(this object source, T target)
where T : class,new()
{
if (source == null)
return;
if (target == null)
{
target = new T();
}
foreach (var property in target.GetType().GetProperties())
{
var propertyValue = source.GetType().GetProperty(property.Name).GetValue(source, null);
if (propertyValue != null)
{
if (propertyValue.GetType().IsClass)
{
}
target.GetType().InvokeMember(property.Name, BindingFlags.SetProperty, null, target, new object[] { propertyValue });
}
}
foreach (var field in target.GetType().GetFields())
{
var fieldValue = source.GetType().GetField(field.Name).GetValue(source);
if (fieldValue != null)
{
target.GetType().InvokeMember(field.Name, BindingFlags.SetField, null, target, new object[] { fieldValue });
}
}
}
}
}

View File

@@ -0,0 +1,712 @@
using System.Xml;
/// 这个是用VS2010写的如果用VS2005请去掉System.Linq和System.Xml.Linq的引用
/// 可以将此文件直接编译成dll今后程序只需要引用该dll后开头添加using XmlLibrary;即可。
namespace Infrastructure.Helpers
{
/// <summary>
/// XMLHelper参数
/// </summary>
public class XmlParameter
{
private string _name;
private string _innerText;
private string _namespaceOfPrefix;
private AttributeParameter[] _attributes;
public XmlParameter() { }
public XmlParameter(string name, params AttributeParameter[] attParas) : this(name, null, null, attParas) { }
public XmlParameter(string name, string innerText, params AttributeParameter[] attParas) : this(name, innerText, null, attParas) { }
public XmlParameter(string name, string innerText, string namespaceOfPrefix, params AttributeParameter[] attParas)
{
this._name = name;
this._innerText = innerText;
this._namespaceOfPrefix = namespaceOfPrefix;
this._attributes = attParas;
}
/// <summary>
/// 节点名称
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
/// <summary>
/// 节点文本
/// </summary>
public string InnerText
{
get { return this._innerText; }
set { this._innerText = value; }
}
/// <summary>
/// 节点前缀xmlns声明(命名空间URI)
/// </summary>
public string NamespaceOfPrefix
{
get { return this._namespaceOfPrefix; }
set { this._namespaceOfPrefix = value; }
}
/// <summary>
/// 节点属性集
/// </summary>
public AttributeParameter[] Attributes
{
get { return this._attributes; }
set { this._attributes = value; }
}
}
/// <summary>
/// 节点属性参数
/// </summary>
public class AttributeParameter
{
private string _name;
private string _value;
public AttributeParameter() { }
public AttributeParameter(string attributeName, string attributeValue)
{
this._name = attributeName;
this._value = attributeValue;
}
/// <summary>
/// 属性名称
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
/// <summary>
/// 属性值
/// </summary>
public string Value
{
get { return this._value; }
set { this._value = value; }
}
}
public class XMLHelper
{
private static string _xPath;
/// <summary>
/// xml文件路径
/// </summary>
public static string XmlPath
{
get { return _xPath; }
set { _xPath = value; }
}
private static string _configName = "XmlPath";
/// <summary>
/// 配置文件节点名称请设置在AppSettings节点下
/// </summary>
public static string ConfigName
{
get { return _configName; }
set { _configName = value; GetConfig(); }
}
/// <summary>
/// 从配置文件读取xml路径
/// </summary>
static void GetConfig()
{
//if (string.IsNullOrEmpty(_xPath))
//{
// try
// {
// _xPath = ConfigurationManager.AppSettings[_configName];
// }
// catch { }
//}
}
static XMLHelper() { GetConfig(); }
#region private AppendChild
/// <summary>
/// 添加一个子节点
/// </summary>
/// <param name="xDoc">XmlDocument对象</param>
/// <param name="parentNode">父节点</param>
/// <param name="xlParameter">Xml参数</param>
private static void AppendChild(XmlDocument xDoc, XmlNode parentNode, params XmlParameter[] xlParameter)
{
foreach (XmlParameter xpar in xlParameter)
{
XmlNode newNode = xDoc.CreateNode(XmlNodeType.Element, xpar.Name, null);
string ns = string.IsNullOrEmpty(xpar.NamespaceOfPrefix) ? "" : newNode.GetNamespaceOfPrefix(xpar.NamespaceOfPrefix);
foreach (AttributeParameter attp in xpar.Attributes)
{
XmlNode attr = xDoc.CreateNode(XmlNodeType.Attribute, attp.Name, ns == "" ? null : ns);
attr.Value = attp.Value;
newNode.Attributes.SetNamedItem(attr);
}
newNode.InnerText = xpar.InnerText;
parentNode.AppendChild(newNode);
}
}
#endregion
#region private AddEveryNode
private static void AddEveryNode(XmlDocument xDoc, XmlNode parentNode, params XmlParameter[] paras)
{
XmlNodeList nlst = xDoc.DocumentElement.ChildNodes;
foreach (XmlNode xns in nlst)
{
if (xns.Name == parentNode.Name)
{
AppendChild(xDoc, xns, paras);
}
else
{
foreach (XmlNode xn in xns)
{
if (xn.Name == parentNode.Name)
{
AppendChild(xDoc, xn, paras);
}
}
}
}
}
#endregion
#region private GetXmlDom
/// <summary>
/// 获得一个XmlDocument对象
/// </summary>
/// <returns></returns>
private static XmlDocument GetXmlDom()
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(_xPath);
return xdoc;
}
#endregion
#region CreateXmlFile
/// <summary>
/// 创建一个XML文档成功创建后操作路径将直接指向该文件
/// </summary>
/// <param name="fileName">文件物理路径名</param>
/// <param name="rootNode">根结点名称</param>
/// <param name="elementName">元素节点名称</param>
/// <param name="xmlParameter">XML参数</param>
public static void CreateXmlFile(string fileName, string rootNode, string elementName, params XmlParameter[] xmlParameter)
{
XmlDocument xDoc = new XmlDocument();
XmlNode xn = xDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
xDoc.AppendChild(xn);
XmlNode root = xDoc.CreateElement(rootNode);
xDoc.AppendChild(root);
XmlNode ln = xDoc.CreateNode(XmlNodeType.Element, elementName, null);
AppendChild(xDoc, ln, xmlParameter);
root.AppendChild(ln);
try
{
xDoc.Save(fileName);
_xPath = fileName;
}
catch
{
throw;
}
}
/// <summary>
/// 创建一个XML文档成功创建后操作路径将直接指向该文件
/// </summary>
/// <param name="fileName">文件物理路径名</param>
/// <param name="xmlString">xml字符串</param>
public static void CreateXmlFile(string fileName, string xmlString)
{
XmlDocument xDoc = new XmlDocument();
try
{
xDoc.LoadXml(xmlString);
xDoc.Save(fileName);
_xPath = fileName;
}
catch { throw; }
}
#endregion
#region AddNewNode
/// <summary>
/// 添加新节点
/// </summary>
/// <param name="parentNode">新节点的父节点对象</param>
/// <param name="xmlParameter">Xml参数对象</param>
public static void AddNewNode(XmlNode parentNode, params XmlParameter[] xmlParameter)
{
XmlDocument xDoc = GetXmlDom();
if (parentNode.Name == xDoc.DocumentElement.Name)
{
XmlNode newNode = xDoc.CreateNode(XmlNodeType.Element, xDoc.DocumentElement.ChildNodes[0].Name, null);
AppendChild(xDoc, newNode, xmlParameter);
xDoc.DocumentElement.AppendChild(newNode);
}
else
{
AddEveryNode(xDoc, parentNode, xmlParameter);
}
xDoc.Save(_xPath);
}
/// <summary>
/// 添加新节点
/// </summary>
/// <param name="xDoc">XmlDocument对象</param>
/// <param name="parentName">新节点的父节点名称</param>
/// <param name="xmlParameter">XML参数对象</param>
public static void AddNewNode(string parentName, params XmlParameter[] xmlParameter)
{
XmlDocument xDoc = GetXmlDom();
XmlNode parentNode = GetNode(xDoc, parentName);
if (parentNode == null) return;
if (parentNode.Name == xDoc.DocumentElement.Name)
{
XmlNode newNode = xDoc.CreateNode(XmlNodeType.Element, xDoc.DocumentElement.ChildNodes[0].Name, null);
AppendChild(xDoc, newNode, xmlParameter);
xDoc.DocumentElement.AppendChild(newNode);
}
else
{
AddEveryNode(xDoc, parentNode, xmlParameter);
}
xDoc.Save(_xPath);
}
#endregion
#region AddAttribute
/// <summary>
/// 添加节点属性
/// </summary>
/// <param name="node">节点对象</param>
/// <param name="namespaceOfPrefix">该节点的命名空间URI</param>
/// <param name="attributeName">新属性名称</param>
/// <param name="attributeValue">属性值</param>
public static void AddAttribute(XmlNode node, string namespaceOfPrefix, string attributeName, string attributeValue)
{
XmlDocument xDoc = GetXmlDom();
string ns = string.IsNullOrEmpty(namespaceOfPrefix) ? "" : node.GetNamespaceOfPrefix(namespaceOfPrefix);
XmlNode xn = xDoc.CreateNode(XmlNodeType.Attribute, attributeName, ns == "" ? null : ns);
xn.Value = attributeValue;
node.Attributes.SetNamedItem(xn);
xDoc.Save(_xPath);
}
/// <summary>
/// 添加节点属性
/// </summary>
/// <param name="node">节点对象</param>
/// <param name="namespaceOfPrefix">该节点的命名空间URI</param>
/// <param name="attributeParameters">节点属性参数</param>
public static void AddAttribute(XmlNode node, string namespaceOfPrefix, params AttributeParameter[] attributeParameters)
{
XmlDocument xDoc = GetXmlDom();
string ns = string.IsNullOrEmpty(namespaceOfPrefix) ? "" : node.GetNamespaceOfPrefix(namespaceOfPrefix);
foreach (AttributeParameter attp in attributeParameters)
{
XmlNode xn = xDoc.CreateNode(XmlNodeType.Attribute, attp.Name, ns == "" ? null : ns);
xn.Value = attp.Value;
node.Attributes.SetNamedItem(xn);
}
xDoc.Save(_xPath);
}
/// <summary>
/// 添加节点属性
/// </summary>
/// <param name="nodeName">节点名称</param>
/// <param name="namespaceOfPrefix">该节点的命名空间URI</param>
/// <param name="attributeName">新属性名称</param>
/// <param name="attributeValue">属性值</param>
public static void AddAttribute(string nodeName, string namespaceOfPrefix, string attributeName, string attributeValue)
{
XmlDocument xDoc = GetXmlDom();
XmlNodeList xlst = xDoc.DocumentElement.ChildNodes;
for (int i = 0; i < xlst.Count; i++)
{
XmlNode node = GetNode(xlst[i], nodeName);
if (node == null) break;
AddAttribute(node, namespaceOfPrefix, attributeName, attributeValue);
}
xDoc.Save(_xPath);
}
/// <summary>
/// 添加节点属性
/// </summary>
/// <param name="nodeName">节点名称</param>
/// <param name="namespaceOfPrefix">该节点的命名空间URI</param>
/// <param name="attributeParameters">节点属性参数</param>
public static void AddAttribute(string nodeName, string namespaceOfPrefix, params AttributeParameter[] attributeParameters)
{
XmlDocument xDoc = GetXmlDom();
XmlNodeList xlst = xDoc.DocumentElement.ChildNodes;
for (int i = 0; i < xlst.Count; i++)
{
XmlNode node = GetNode(xlst[i], nodeName);
if (node == null) break;
AddAttribute(node, namespaceOfPrefix, attributeParameters);
}
xDoc.Save(_xPath);
}
#endregion
#region GetNode
/// <summary>
/// 获取指定节点名称的节点对象
/// </summary>
/// <param name="nodeName">节点名称</param>
/// <returns></returns>
public static XmlNode GetNode(string nodeName)
{
XmlDocument xDoc = GetXmlDom();
if (xDoc.DocumentElement.Name == nodeName) return (XmlNode)xDoc.DocumentElement;
XmlNodeList nlst = xDoc.DocumentElement.ChildNodes;
foreach (XmlNode xns in nlst) // 遍历所有子节点
{
if (xns.Name == nodeName) return xns;
else
{
XmlNode xn = GetNode(xns, nodeName);
if (xn != null) return xn; /// V1.0.0.3添加节点判断
}
}
return null;
}
/// <summary>
/// 获取指定节点名称的节点对象
/// </summary>
/// <param name="node">节点对象</param>
/// <param name="nodeName">节点名称</param>
/// <returns></returns>
public static XmlNode GetNode(XmlNode node, string nodeName)
{
foreach (XmlNode xn in node)
{
if (xn.Name == nodeName) return xn;
else
{
XmlNode tmp = GetNode(xn, nodeName);
if (tmp != null) return tmp;
}
}
return null;
}
/// <summary>
/// 获取指定节点名称的节点对象
/// </summary>
/// <param name="index">节点索引</param>
/// <param name="nodeName">节点名称</param>
public static XmlNode GetNode(int index, string nodeName)
{
XmlDocument xDoc = GetXmlDom();
XmlNodeList nlst = xDoc.DocumentElement.ChildNodes;
if (nlst.Count <= index) return null;
if (nlst[index].Name == nodeName) return (XmlNode)nlst[index];
foreach (XmlNode xn in nlst[index])
{
return GetNode(xn, nodeName);
}
return null;
}
/// <summary>
/// 获取指定节点名称的节点对象
/// </summary>
/// <param name="node">节点对象</param>
/// <param name="nodeName">节点名称</param>
/// <param name="innerText">节点内容</param>
public static XmlNode GetNode(XmlNode node, string nodeName, string innerText)
{
foreach (XmlNode xn in node)
{
if (xn.Name == nodeName && xn.InnerText == innerText) return xn;
else
{
XmlNode tmp = GetNode(xn, nodeName, innerText);
if (tmp != null) return tmp;
}
}
return null;
}
/// <summary>
/// 获取指定节点名称的节点对象
/// </summary>
/// <param name="nodeName">节点名称</param>
/// <param name="innerText">节点内容</param>
public static XmlNode GetNode(string nodeName, string innerText)
{
XmlDocument xDoc = GetXmlDom();
XmlNodeList nlst = xDoc.DocumentElement.ChildNodes;
foreach (XmlNode xns in nlst) // 遍历所有子节点
{
if (xns.Name == nodeName && xns.InnerText == innerText) return xns;
XmlNode tmp = GetNode(xns, nodeName, innerText);
if (tmp != null) return tmp;
}
return null;
}
/// <summary>
/// 获取指定节点名称的节点对象
/// </summary>
/// <param name="xmlParameter">XML参数</param>
public static XmlNode GetNode(XmlParameter xmlParameter)
{
return GetNode(xmlParameter.Name, xmlParameter.InnerText);
}
/// <summary>
/// 获取指定节点名称的节点对象
/// </summary>
/// <param name="node">节点对象</param>
/// <param name="xmlParameter">XML参数</param>
public static XmlNode GetNode(XmlNode node, XmlParameter xmlParameter)
{
return GetNode(node, xmlParameter.Name, node.InnerText);
}
#endregion
#region UpdateNode
private static void UpdateNode(XmlNode node, XmlParameter xmlParameter)
{
node.InnerText = xmlParameter.InnerText;
for (int i = 0; i < xmlParameter.Attributes.Length; i++)
{
for (int j = 0; j < node.Attributes.Count; j++)
{
if (node.Attributes[j].Name == xmlParameter.Attributes[i].Name)
{
node.Attributes[j].Value = xmlParameter.Attributes[i].Value;
}
}
}
}
private static void UpdateNode(XmlNode node, string innerText, AttributeParameter[] attributeParameters)
{
node.InnerText = innerText;
for (int i = 0; i < attributeParameters.Length; i++)
{
for (int j = 0; j < node.Attributes.Count; j++)
{
if (node.Attributes[j].Name == attributeParameters[i].Name)
{
node.Attributes[j].Value = attributeParameters[i].Value;
}
}
}
}
/// <summary>
/// 修改节点的内容
/// </summary>
/// <param name="index">节点索引</param>
/// <param name="xmlParameter">XML参数对象</param>
public static void UpdateNode(int index, XmlParameter xmlParameter)
{
XmlDocument xDoc = GetXmlDom();
XmlNodeList nlst = xDoc.DocumentElement.ChildNodes;
if (nlst.Count <= index) return;
if (nlst[index].Name == xmlParameter.Name)
{
UpdateNode(nlst[index], xmlParameter);
}
else
{
foreach (XmlNode xn in nlst[index])
{
XmlNode xnd = GetNode(xn, xmlParameter.Name);
if (xnd != null)
{
UpdateNode(xnd, xmlParameter);
}
}
}
xDoc.Save(_xPath);
}
/// <summary>
/// 修改节点的内容
/// </summary>
/// <param name="index">节点索引</param>
/// <param name="nodeName">节点名称</param>
/// <param name="newInnerText">修改后的内容</param>
public static void UpdateNode(int index, string nodeName, string newInnerText)
{
XmlDocument xDoc = GetXmlDom();
XmlNodeList nlst = xDoc.DocumentElement.ChildNodes;
if (nlst.Count <= index) return;
if (nlst[index].Name == nodeName)
{
nlst[index].InnerText = newInnerText;
}
else
{
foreach (XmlNode xn in nlst[index])
{
XmlNode xnd = GetNode(xn, nodeName);
if (xnd != null)
{
xnd.InnerText = newInnerText;
}
}
}
xDoc.Save(_xPath);
}
/// <summary>
/// 修改节点的内容
/// </summary>
/// <param name="xmlParameter">XmlParameter对象</param>
/// <param name="innerText">修改后的内容</param>
/// <param name="attributeParameters">需要修改的属性</param>
public static void UpdateNode(XmlParameter xmlParameter, string innerText, params AttributeParameter[] attributeParameters)
{
XmlDocument xDoc = GetXmlDom();
XmlNodeList nlst = xDoc.DocumentElement.ChildNodes;
foreach (XmlNode xns in nlst) // 遍历所有子节点
{
if (xns.Name == xmlParameter.Name && xns.InnerText == xmlParameter.InnerText)
{
UpdateNode(xns, innerText, attributeParameters);
break;
}
XmlNode tmp = GetNode(xns, xmlParameter);
if (tmp != null)
{
UpdateNode(tmp, innerText, attributeParameters);
break;
}
}
xDoc.Save(_xPath);
}
#endregion
#region DeleteNode
/// <summary>
/// 删除节点
/// </summary>
/// <param name="index">节点索引</param>
public static void DeleteNode(int index)
{
XmlDocument xDoc = GetXmlDom();
XmlNodeList nlst = xDoc.DocumentElement.ChildNodes;
nlst[index].ParentNode.RemoveChild(nlst[index]);
xDoc.Save(_xPath);
}
/// <summary>
/// 删除节点
/// </summary>
/// <param name="nodeList">需要删除的节点对象</param>
public static void DeleteNode(params XmlNode[] nodeList)
{
XmlDocument xDoc = GetXmlDom();
foreach (XmlNode xnl in nodeList)
{
foreach (XmlNode xn in xDoc.DocumentElement.ChildNodes)
{
if (xnl.Equals(xn))
{
xn.ParentNode.RemoveChild(xn);
break;
}
}
}
xDoc.Save(_xPath);
}
/// <summary>
/// 删除节点
/// </summary>
/// <param name="xDoc">XmlDocument对象</param>
/// <param name="nodeName">节点名称</param>
/// <param name="nodeText">节点内容</param>
public static void DeleteNode(string nodeName, string nodeText)
{
XmlDocument xDoc = GetXmlDom();
foreach (XmlNode xn in xDoc.DocumentElement.ChildNodes)
{
if (xn.Name == nodeName)
{
if (xn.InnerText == nodeText)
{
xn.ParentNode.RemoveChild(xn);
return;
}
}
else
{
XmlNode node = GetNode(xn, nodeName);
if (node != null && node.InnerText == nodeText)
{
node.ParentNode.ParentNode.RemoveChild(node.ParentNode);
return;
}
}
}
xDoc.Save(_xPath);
}
#endregion
#region SetAttribute
/// <summary>
/// 修改属性值
/// </summary>
/// <param name="elem">元素对象</param>
/// <param name="attps">属性参数</param>
private static void SetAttribute(XmlElement elem, params AttributeParameter[] attps)
{
foreach (AttributeParameter attp in attps)
{
elem.SetAttribute(attp.Name, attp.Value);
}
}
/// <summary>
/// 修改属性值
/// </summary>
/// <param name="xmlParameter">XML参数</param>
/// <param name="attributeParameters">属性参数</param>
public static void SetAttribute(XmlParameter xmlParameter, params AttributeParameter[] attributeParameters)
{
XmlDocument xDoc = GetXmlDom();
XmlNodeList nlst = xDoc.DocumentElement.ChildNodes;
foreach (XmlNode xns in nlst) // 遍历所有子节点
{
if (xns.Name == xmlParameter.Name && xns.InnerText == xmlParameter.InnerText)
{
SetAttribute((XmlElement)xns, attributeParameters);
break;
}
XmlNode tmp = GetNode(xns, xmlParameter);
if (tmp != null)
{
SetAttribute((XmlElement)tmp, attributeParameters);
break;
}
}
xDoc.Save(_xPath);
}
/// <summary>
/// 修改属性值
/// </summary>
/// <param name="xmlParameter">XML参数</param>
/// <param name="attributeValue">新属性值</param>
public static void SetAttribute(XmlParameter xmlParameter, string attributeName, string attributeValue)
{
XmlDocument xDoc = GetXmlDom();
XmlNodeList nlst = xDoc.DocumentElement.ChildNodes;
foreach (XmlNode xns in nlst) // 遍历所有子节点
{
if (xns.Name == xmlParameter.Name && xns.InnerText == xmlParameter.InnerText)
{
((XmlElement)xns).SetAttribute(attributeName, attributeValue);
break;
}
XmlNode tmp = GetNode(xns, xmlParameter);
if (tmp != null)
{
((XmlElement)tmp).SetAttribute(attributeName, attributeValue);
break;
}
}
xDoc.Save(_xPath);
}
#endregion
}
}