初始化版本

This commit is contained in:
LL
2025-11-14 16:12:32 +08:00
commit ea40f18aa6
326 changed files with 137063 additions and 0 deletions

View File

@@ -0,0 +1,74 @@
/********************************************************************
* *
* * Copyright (C) 2013-2018 uiskin.cn
* * 作者: BinGoo QQ315567586
* * 请尊重作者劳动成果,请保留以上作者信息,禁止用于商业活动。
* *
* * 创建时间2014-08-05
* * 说明:应用程序帮助类
* *
********************************************************************/
using System.Diagnostics;
using System.Threading;
namespace NetWorkHelper.Helper
{
public static class ApplicationHelper
{
#region
/// <summary>
/// 启动一个应用程序或进程
/// </summary>
/// <param name="appFilePath">程序或线程的路径</param>
public static void StartApplication(string appFilePath)
{
Process downprocess = new Process();
downprocess.StartInfo.FileName = appFilePath;
downprocess.Start();
}
#endregion
#region
/// <summary>
/// 目标应用程序是否已经启动。通常用于判断单实例应用。将占用锁。
/// </summary>
/// <param name="instanceName">应用名称</param>
/// <returns></returns>
public static bool IsAppInstanceExist(string instanceName)
{
bool createdNew = false;
ApplicationHelper.MutexForSingletonExe = new Mutex(false, instanceName, out createdNew);
return (!createdNew);
}
public static System.Threading.Mutex MutexForSingletonExe = null;
/// <summary>
/// 释放进程中占用的程序。
/// </summary>
/// <param name="instanceName"></param>
public static void ReleaseAppInstance(string instanceName)
{
if (ApplicationHelper.MutexForSingletonExe != null)
{
ApplicationHelper.MutexForSingletonExe.Close();
ApplicationHelper.MutexForSingletonExe = null;
}
}
#endregion
#region
/// <summary>
/// 在浏览器中打开Url链接
/// </summary>
/// <param name="url"></param>
public static void OpenUrl(string url)
{
Process.Start(url);
}
#endregion
}
}

View File

@@ -0,0 +1,259 @@
using NetWorkHelper.ICollections;
using System;
using System.Collections.Generic;
namespace NetWorkHelper.Helper
{
public static class CollectionHelper
{
#region Find
/// <summary>
/// Find 从集合中选取符合条件的元素
/// </summary>
public static List<TObject> Find<TObject>(IEnumerable<TObject> source, Predicate<TObject> predicate)
{
List<TObject> list = new List<TObject>();
CollectionHelper.ActionOnSpecification(source, delegate (TObject ele) { list.Add(ele); }, predicate);
return list;
}
#endregion
#region FindFirstSpecification
/// <summary>
/// FindFirstSpecification 返回符合条件的第一个元素
/// </summary>
public static TObject FindFirstSpecification<TObject>(IEnumerable<TObject> source, Predicate<TObject> predicate)
{
foreach (TObject element in source)
{
if (predicate(element))
{
return element;
}
}
return default(TObject);
}
#endregion
#region ContainsSpecification
/// <summary>
/// ContainsSpecification 集合中是否包含满足predicate条件的元素。
/// </summary>
public static bool ContainsSpecification<TObject>(IEnumerable<TObject> source, Predicate<TObject> predicate, out TObject specification)
{
specification = default(TObject);
foreach (TObject element in source)
{
if (predicate(element))
{
specification = element;
return true;
}
}
return false;
}
/// <summary>
/// ContainsSpecification 集合中是否包含满足predicate条件的元素。
/// </summary>
public static bool ContainsSpecification<TObject>(IEnumerable<TObject> source, Predicate<TObject> predicate)
{
TObject specification;
return CollectionHelper.ContainsSpecification<TObject>(source, predicate, out specification);
}
#endregion
#region ActionOnSpecification
/// <summary>
/// ActionOnSpecification 对集合中满足predicate条件的元素执行action。如果没有条件predicate传入null。
/// </summary>
public static void ActionOnSpecification<TObject>(IEnumerable<TObject> collection, Action<TObject> action, Predicate<TObject> predicate)
{
if (collection == null)
{
return;
}
if (predicate == null)
{
foreach (TObject obj in collection)
{
action(obj);
}
return;
}
foreach (TObject obj in collection)
{
if (predicate(obj))
{
action(obj);
}
}
}
#endregion
#region ActionOnEach
/// <summary>
/// ActionOnEach 对集合中的每个元素执行action。
/// </summary>
public static void ActionOnEach<TObject>(IEnumerable<TObject> collection, Action<TObject> action)
{
CollectionHelper.ActionOnSpecification<TObject>(collection, action, null);
}
#endregion
#region GetPart
public static T[] GetPart<T>(T[] ary, int startIndex, int count)
{
return CollectionHelper.GetPart<T>(ary, startIndex, count, false);
}
public static T[] GetPart<T>(T[] ary, int startIndex, int count, bool reverse)
{
if (startIndex >= ary.Length)
{
return null;
}
if (ary.Length < startIndex + count)
{
count = ary.Length - startIndex;
}
T[] result = new T[count];
if (!reverse)
{
for (int i = 0; i < count; i++)
{
result[i] = ary[startIndex + i];
}
}
else
{
for (int i = 0; i < count; i++)
{
result[i] = ary[ary.Length - startIndex - 1 - i];
}
}
return result;
}
#endregion
#region BinarySearch
/// <summary>
/// BinarySearch 从已排序的列表中,采用二分查找找到目标在列表中的位置。
/// 如果刚好有个元素与目标相等则返回true且minIndex会被赋予该元素的位置否则返回false且minIndex会被赋予比目标小且最接近目标的元素的位置
/// </summary>
public static bool BinarySearch<T>(IList<T> sortedList, T target, out int minIndex) where T : IComparable
{
if (target.CompareTo(sortedList[0]) == 0)
{
minIndex = 0;
return true;
}
if (target.CompareTo(sortedList[0]) < 0)
{
minIndex = -1;
return false;
}
if (target.CompareTo(sortedList[sortedList.Count - 1]) == 0)
{
minIndex = sortedList.Count - 1;
return true;
}
if (target.CompareTo(sortedList[sortedList.Count - 1]) > 0)
{
minIndex = sortedList.Count - 1;
return false;
}
int targetPosIndex = -1;
int left = 0;
int right = sortedList.Count - 1;
while (right - left > 1)
{
int middle = (left + right) / 2;
if (target.CompareTo(sortedList[middle]) == 0)
{
minIndex = middle;
return true;
}
if (target.CompareTo(sortedList[middle]) < 0)
{
right = middle;
}
else
{
left = middle;
}
}
minIndex = left;
return false;
}
#endregion
#region GetIntersection GetUnion
/// <summary>
/// GetIntersection 高效地求两个List元素的交集。
/// </summary>
public static List<T> GetIntersection<T>(List<T> list1, List<T> list2) where T : IComparable
{
List<T> largList = list1.Count > list2.Count ? list1 : list2;
List<T> smallList = largList == list1 ? list2 : list1;
largList.Sort();
int minIndex = 0;
List<T> result = new List<T>();
foreach (T tmp in smallList)
{
if (CollectionHelper.BinarySearch<T>(largList, tmp, out minIndex))
{
result.Add(tmp);
}
}
return result;
}
/// <summary>
/// GetUnion 高效地求两个List元素的并集。
/// </summary>
public static List<T> GetUnion<T>(List<T> list1, List<T> list2)
{
SortedDictionary<T, int> result = new SortedDictionary<T, int>();
foreach (T tmp in list1)
{
if (!result.ContainsKey(tmp))
{
result.Add(tmp, 0);
}
}
foreach (T tmp in list2)
{
if (!result.ContainsKey(tmp))
{
result.Add(tmp, 0);
}
}
return (List<T>)CollectionConverter.CopyAllToList<T>(result.Keys);
}
#endregion
}
}

View File

@@ -0,0 +1,134 @@
using System;
using System.Text;
namespace NetWorkHelper.Helper
{
public class DataFrame
{
DataFrameHeader _header;
private byte[] _extend = new byte[0];
private byte[] _mask = new byte[0];
private byte[] _content = new byte[0];
public DataFrame(byte[] buffer)
{
//帧头
_header = new DataFrameHeader(buffer);
//扩展长度
if (_header.Length == 126)
{
_extend = new byte[2];
Buffer.BlockCopy(buffer, 2, _extend, 0, 2);
}
else if (_header.Length == 127)
{
_extend = new byte[8];
Buffer.BlockCopy(buffer, 2, _extend, 0, 8);
}
//是否有掩码
if (_header.HasMask)
{
_mask = new byte[4];
Buffer.BlockCopy(buffer, _extend.Length + 2, _mask, 0, 4);
}
//消息体
if (_extend.Length == 0)
{
_content = new byte[_header.Length];
Buffer.BlockCopy(buffer, _extend.Length + _mask.Length + 2, _content, 0, _content.Length);
}
else if (_extend.Length == 2)
{
int contentLength = (int)_extend[0] * 256 + (int)_extend[1];
_content = new byte[contentLength];
Buffer.BlockCopy(buffer, _extend.Length + _mask.Length + 2, _content, 0, contentLength > 1024 * 100 ? 1024 * 100 : contentLength);
}
else
{
long len = 0;
int n = 1;
for (int i = 7; i >= 0; i--)
{
len += (int)_extend[i] * n;
n *= 256;
}
_content = new byte[len];
Buffer.BlockCopy(buffer, _extend.Length + _mask.Length + 2, _content, 0, _content.Length);
}
if (_header.HasMask) _content = Mask(_content, _mask);
}
public DataFrame(string content)
{
_content = Encoding.UTF8.GetBytes(content);
int length = _content.Length;
if (length < 126)
{
_extend = new byte[0];
_header = new DataFrameHeader(true, false, false, false, 1, false, length);
}
else if (length < 65536)
{
_extend = new byte[2];
_header = new DataFrameHeader(true, false, false, false, 1, false, 126);
_extend[0] = (byte)(length / 256);
_extend[1] = (byte)(length % 256);
}
else
{
_extend = new byte[8];
_header = new DataFrameHeader(true, false, false, false, 1, false, 127);
int left = length;
int unit = 256;
for (int i = 7; i > 1; i--)
{
_extend[i] = (byte)(left % unit);
left = left / unit;
if (left == 0)
break;
}
}
}
public byte[] GetBytes()
{
byte[] buffer = new byte[2 + _extend.Length + _mask.Length + _content.Length];
Buffer.BlockCopy(_header.GetBytes(), 0, buffer, 0, 2);
Buffer.BlockCopy(_extend, 0, buffer, 2, _extend.Length);
Buffer.BlockCopy(_mask, 0, buffer, 2 + _extend.Length, _mask.Length);
Buffer.BlockCopy(_content, 0, buffer, 2 + _extend.Length + _mask.Length, _content.Length);
return buffer;
}
public string Text
{
get
{
if (_header.OpCode != 1)
return string.Empty;
return Encoding.UTF8.GetString(_content);
}
}
private byte[] Mask(byte[] data, byte[] mask)
{
for (var i = 0; i < data.Length; i++)
{
data[i] = (byte)(data[i] ^ mask[i % 4]);
}
return data;
}
}
}

View File

@@ -0,0 +1,80 @@
using System;
namespace NetWorkHelper.Helper
{
public class DataFrameHeader
{
private bool _fin;
private bool _rsv1;
private bool _rsv2;
private bool _rsv3;
private sbyte _opcode;
private bool _maskcode;
private sbyte _payloadlength;
public bool FIN { get { return _fin; } }
public bool RSV1 { get { return _rsv1; } }
public bool RSV2 { get { return _rsv2; } }
public bool RSV3 { get { return _rsv3; } }
public sbyte OpCode { get { return _opcode; } }
public bool HasMask { get { return _maskcode; } }
public sbyte Length { get { return _payloadlength; } }
public DataFrameHeader(byte[] buffer)
{
if (buffer.Length < 2)
throw new Exception("无效的数据头.");
//第一个字节
_fin = (buffer[0] & 0x80) == 0x80;
_rsv1 = (buffer[0] & 0x40) == 0x40;
_rsv2 = (buffer[0] & 0x20) == 0x20;
_rsv3 = (buffer[0] & 0x10) == 0x10;
_opcode = (sbyte)(buffer[0] & 0x0f);
//第二个字节
_maskcode = (buffer[1] & 0x80) == 0x80;
_payloadlength = (sbyte)(buffer[1] & 0x7f);
}
//发送封装数据
public DataFrameHeader(bool fin, bool rsv1, bool rsv2, bool rsv3, sbyte opcode, bool hasmask, int length)
{
_fin = fin;
_rsv1 = rsv1;
_rsv2 = rsv2;
_rsv3 = rsv3;
_opcode = opcode;
//第二个字节
_maskcode = hasmask;
_payloadlength = (sbyte)length;
}
//返回帧头字节
public byte[] GetBytes()
{
byte[] buffer = { 0, 0 };
if (_fin) buffer[0] ^= 0x80;
if (_rsv1) buffer[0] ^= 0x40;
if (_rsv2) buffer[0] ^= 0x20;
if (_rsv3) buffer[0] ^= 0x10;
buffer[0] ^= (byte)_opcode;
if (_maskcode) buffer[1] ^= 0x80;
buffer[1] ^= (byte)_payloadlength;
return buffer;
}
}
}

View File

@@ -0,0 +1,571 @@
/********************************************************************
* *
* * Copyright (C) 2013-2018 uiskin.cn
* * 作者: BinGoo QQ315567586
* * 请尊重作者劳动成果,请保留以上作者信息,禁止用于商业活动。
* *
* * 创建时间2014-08-05
* * 说明:文件操作类
* *
********************************************************************/
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace NetWorkHelper.Helper
{
public static class FileHelper
{
#region
/// <summary>
/// 将字符串写成文件
/// </summary>
public static void GenerateFile(string filePath, string text)
{
string directoryPath = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.Write(text);
sw.Flush();
sw.Close();
fs.Close();
}
#endregion
#region
/// <summary>
/// 读取文本文件的内容
/// </summary>
public static string GetFileContent(string file_path)
{
if (!File.Exists(file_path))
{
return null;
}
StreamReader reader = new StreamReader(file_path, Encoding.UTF8);
string content = reader.ReadToEnd();
reader.Close();
return content;
}
#endregion
#region
/// <summary>
/// 将二进制数据写入文件中
/// </summary>
public static void WriteBuffToFile(byte[] buff, int offset, int len, string filePath)
{
string directoryPath = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buff, offset, len);
bw.Flush();
bw.Close();
fs.Close();
}
/// <summary>
/// WriteBuffToFile 将二进制数据写入文件中
/// </summary>
public static void WriteBuffToFile(byte[] buff, string filePath)
{
string directoryPath = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buff);
bw.Flush();
bw.Close();
fs.Close();
}
#endregion
#region
/// <summary>
/// 从文件中读取二进制数据
/// </summary>
public static byte[] ReadFileReturnBytes(string filePath)
{
if (!File.Exists(filePath))
{
return null;
}
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryReader br = new BinaryReader(fs);
byte[] buff = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
return buff;
}
#endregion
#region
/// <summary>
/// 获取要打开的文件路径
/// </summary>
public static string GetFileToOpen(string title)
{
OpenFileDialog openDlg = new OpenFileDialog();
openDlg.Filter = "All Files (*.*)|*.*";
openDlg.FileName = "";
if (title != null)
{
openDlg.Title = title;
}
openDlg.CheckFileExists = true;
openDlg.CheckPathExists = true;
DialogResult res = openDlg.ShowDialog();
if (res == DialogResult.OK)
{
return openDlg.FileName;
}
return null;
}
/// <summary>
/// 获取要打开的文件路径
/// </summary>
/// <param name="title">对话框标题</param>
/// <param name="iniDir">初始目录</param>
/// <param name="extendName">文件类型</param>
/// <returns></returns>
public static string GetFileToOpen(string title, string iniDir, string extendName)
{
return GetFileToOpen2(title, iniDir, extendName);
}
/// <summary>
/// 获取要打开的文件路径
/// </summary>
/// <param name="title">对话框标题</param>
/// <param name="iniDir">初始目录</param>
/// <param name="extendNames">文件类型</param>
/// <returns></returns>
public static string GetFileToOpen2(string title, string iniDir, params string[] extendNames)
{
StringBuilder filterBuilder = new StringBuilder("(");
for (int i = 0; i < extendNames.Length; i++)
{
filterBuilder.Append("*");
filterBuilder.Append(extendNames[i]);
if (i < extendNames.Length - 1)
{
filterBuilder.Append(";");
}
else
{
filterBuilder.Append(")");
}
}
filterBuilder.Append("|");
for (int i = 0; i < extendNames.Length; i++)
{
filterBuilder.Append("*");
filterBuilder.Append(extendNames[i]);
if (i < extendNames.Length - 1)
{
filterBuilder.Append(";");
}
}
OpenFileDialog openDlg = new OpenFileDialog();
openDlg.Filter = filterBuilder.ToString();
openDlg.FileName = "";
openDlg.InitialDirectory = iniDir;
if (title != null)
{
openDlg.Title = title;
}
openDlg.CheckFileExists = true;
openDlg.CheckPathExists = true;
DialogResult res = openDlg.ShowDialog();
if (res == DialogResult.OK)
{
return openDlg.FileName;
}
return null;
}
#endregion
#region
/// <summary>
/// 获取要打开的文件夹
/// </summary>
/// <param name="newFolderButton">新建文件夹按钮是否显示在浏览文件夹对话框中</param>
/// <returns></returns>
public static string GetFolderToOpen(bool newFolderButton)
{
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.ShowNewFolderButton = newFolderButton;
DialogResult res = folderDialog.ShowDialog();
if (res == DialogResult.OK)
{
return folderDialog.SelectedPath;
}
return null;
}
#endregion
#region
/// <summary>
/// 获取要保存的文件的路径
/// </summary>
/// <param name="title">对话框标题</param>
/// <param name="defaultName">默认名称</param>
/// <param name="iniDir">初始化文件夹</param>
/// <returns></returns>
public static string GetPathToSave(string title, string defaultName, string iniDir)
{
string extendName = Path.GetExtension(defaultName);
SaveFileDialog saveDlg = new SaveFileDialog();
saveDlg.Filter = string.Format("The Files (*{0})|*{0}", extendName);
saveDlg.FileName = defaultName;
saveDlg.InitialDirectory = iniDir;
saveDlg.OverwritePrompt = false;
if (title != null)
{
saveDlg.Title = title;
}
DialogResult res = saveDlg.ShowDialog();
if (res == DialogResult.OK)
{
return saveDlg.FileName;
}
return null;
}
#endregion
#region
/// <summary>
/// 获取不包括路径的文件名
/// </summary>
/// <param name="filePath">指定的文件夹</param>
/// <returns></returns>
public static string GetFileNameNoPath(string filePath)
{
return Path.GetFileName(filePath);
}
#endregion
#region
/// <summary>
/// 获取目标文件的大小
/// </summary>
/// <param name="filePath">文件路径</param>
/// <returns></returns>
public static ulong GetFileSize(string filePath)
{
FileInfo info = new FileInfo(filePath);
return (ulong)info.Length;
}
#endregion
#region
/// <summary>
/// 获取某个文件夹的大小。
/// </summary>
/// <param name="dirPath">文件夹路径</param>
/// <returns></returns>
public static ulong GetDirectorySize(string dirPath)
{
if (!Directory.Exists(dirPath))
{
return 0;
}
ulong len = 0;
DirectoryInfo di = new DirectoryInfo(dirPath);
foreach (FileInfo fi in di.GetFiles())
{
len += (ulong)fi.Length;
}
DirectoryInfo[] dis = di.GetDirectories();
if (dis.Length > 0)
{
for (int i = 0; i < dis.Length; i++)
{
len += FileHelper.GetDirectorySize(dis[i].FullName);
}
}
return len;
}
#endregion
#region
/// <summary>
/// 从文件流中读取指定大小的内容
/// </summary>
/// <param name="fs"></param>
/// <param name="buff"></param>
/// <param name="count"></param>
/// <param name="offset"></param>
public static void ReadFileData(FileStream fs, byte[] buff, int count, int offset)
{
int readCount = 0;
while (readCount < count)
{
int read = fs.Read(buff, offset + readCount, count - readCount);
readCount += read;
}
return;
}
#endregion
#region
/// <summary>
/// 获取文件所在的目录路径
/// </summary>
/// <param name="filePath">文件路径</param>
/// <returns></returns>
public static string GetFileDirectory(string filePath)
{
return Path.GetDirectoryName(filePath);
}
#endregion
#region
/// <summary>
/// 删除文件
/// </summary>
/// <param name="filePath">文件路径</param>
public static void DeleteFile(string filePath)
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
#endregion
#region
/// <summary>
/// 确保扩展名正确
/// </summary>
/// <param name="origin_path">文件名</param>
/// <param name="extend_name">扩展名</param>
/// <returns></returns>
public static string EnsureExtendName(string origin_path, string extend_name)
{
if (Path.GetExtension(origin_path) != extend_name)
{
origin_path += extend_name;
}
return origin_path;
}
#endregion
#region
/// <summary>
/// 创建文件夹
/// </summary>
/// <param name="dirPath">文件夹路径</param>
public static void ClearDirectory(string dirPath)
{
string[] filePaths = Directory.GetFiles(dirPath);
foreach (string file in filePaths)
{
File.Delete(file);
}
foreach (string childDirPath in Directory.GetDirectories(dirPath))
{
FileHelper.DeleteDirectory(childDirPath);
}
}
#endregion
#region
/// <summary>
/// 删除文件夹
/// </summary>
/// <param name="dirPath">文件夹路径</param>
public static void DeleteDirectory(string dirPath)
{
foreach (string filePath in Directory.GetFiles(dirPath))
{
File.Delete(filePath);
}
foreach (string childDirPath in Directory.GetDirectories(dirPath))
{
FileHelper.DeleteDirectory(childDirPath);
}
DirectoryInfo dir = new DirectoryInfo(dirPath);
dir.Refresh();
if ((dir.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
dir.Attributes &= ~FileAttributes.ReadOnly;
}
dir.Delete();
}
#endregion
#region
/// <summary>
/// 将某个文件夹下的多个文件和子文件夹移到另外一个目录中。
/// </summary>
/// <param name="oldParentDirectoryPath">移动之前文件和子文件夹所处的父目录路径</param>
/// <param name="filesBeMoved">被移动的文件名称的集合</param>
/// <param name="directoriesBeMoved">被移动的文件夹名称的集合</param>
/// <param name="newParentDirectoryPath">移往的目标文件夹路径</param>
public static void Move(string oldParentDirectoryPath, IEnumerable<string> filesBeMoved, IEnumerable<string> directoriesBeMoved, string newParentDirectoryPath)
{
if (filesBeMoved != null)
{
foreach (string beMoved in filesBeMoved)
{
string pathOfBeMoved = oldParentDirectoryPath + beMoved;
if (File.Exists(pathOfBeMoved))
{
File.Move(pathOfBeMoved, newParentDirectoryPath + beMoved);
}
}
}
if (directoriesBeMoved != null)
{
foreach (string beMoved in directoriesBeMoved)
{
string pathOfBeMoved = oldParentDirectoryPath + beMoved;
if (Directory.Exists(pathOfBeMoved))
{
Directory.Move(pathOfBeMoved, newParentDirectoryPath + beMoved);
}
}
}
}
#endregion
#region
/// <summary>
/// 拷贝多个文件和文件夹
/// </summary>
/// <param name="sourceParentDirectoryPath">被拷贝的文件和文件夹所处的父目录路径</param>
/// <param name="filesBeCopyed">被复制的文件名称的集合</param>
/// <param name="directoriesCopyed">被复制的文件夹名称的集合</param>
/// <param name="destParentDirectoryPath">目标目录的路径</param>
public static void Copy(string sourceParentDirectoryPath, IEnumerable<string> filesBeCopyed, IEnumerable<string> directoriesCopyed, string destParentDirectoryPath)
{
bool sameParentDir = sourceParentDirectoryPath == destParentDirectoryPath;
if (filesBeCopyed != null)
{
foreach (string beCopyed in filesBeCopyed)
{
string newName = beCopyed;
while (sameParentDir && File.Exists(destParentDirectoryPath + newName))
{
newName = "副本-" + newName;
}
string pathOfBeCopyed = sourceParentDirectoryPath + beCopyed;
if (File.Exists(pathOfBeCopyed))
{
File.Copy(pathOfBeCopyed, destParentDirectoryPath + newName);
}
}
}
if (directoriesCopyed != null)
{
foreach (string beCopyed in directoriesCopyed)
{
string newName = beCopyed;
while (sameParentDir && Directory.Exists(destParentDirectoryPath + newName))
{
newName = "副本-" + newName;
}
string pathOfBeCopyed = sourceParentDirectoryPath + beCopyed;
if (Directory.Exists(pathOfBeCopyed))
{
CopyDirectoryAndFiles(sourceParentDirectoryPath, beCopyed, destParentDirectoryPath, newName);
}
}
}
}
/// <summary>
/// 递归拷贝文件夹以及下面的所有文件
/// </summary>
private static void CopyDirectoryAndFiles(string sourceParentDirectoryPath, string dirBeCopyed, string destParentDirectoryPath, string newDirName)
{
Directory.CreateDirectory(destParentDirectoryPath + newDirName);
DirectoryInfo source = new DirectoryInfo(sourceParentDirectoryPath + dirBeCopyed);
foreach (FileInfo file in source.GetFiles())
{
File.Copy(file.FullName, destParentDirectoryPath + newDirName + "\\" + file.Name);
}
foreach (DirectoryInfo dir in source.GetDirectories())
{
CopyDirectoryAndFiles(sourceParentDirectoryPath + dirBeCopyed + "\\", dir.Name, destParentDirectoryPath + newDirName + "\\", dir.Name);
}
}
#endregion
#region
/// <summary>
/// 获取目标目录下以及其子目录下的所有文件(采用相对路径)
/// </summary>
public static List<string> GetOffspringFiles(string dirPath)
{
List<string> list = new List<string>();
DirectoryInfo dir = new DirectoryInfo(dirPath);
DoGetOffspringFiles(dirPath, dir, ref list);
return list;
}
private static void DoGetOffspringFiles(string rootPath, DirectoryInfo dir, ref List<string> list)
{
foreach (FileInfo file in dir.GetFiles())
{
list.Add(file.FullName.Substring(rootPath.Length));
}
foreach (DirectoryInfo childDir in dir.GetDirectories())
{
DoGetOffspringFiles(rootPath, childDir, ref list);
}
}
#endregion
}
}

View File

@@ -0,0 +1,97 @@
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace NetWorkHelper
{
public static class ImageHelper
{
/// <summary>
/// Convert Image to Byte[]
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public static byte[] ImageToBytes(Image image)
{
ImageFormat format = image.RawFormat;
using (MemoryStream ms = new MemoryStream())
{
if (format.Equals(ImageFormat.Jpeg))
{
image.Save(ms, ImageFormat.Jpeg);
}
else if (format.Equals(ImageFormat.Png))
{
image.Save(ms, ImageFormat.Png);
}
else if (format.Equals(ImageFormat.Bmp))
{
image.Save(ms, ImageFormat.Bmp);
}
else if (format.Equals(ImageFormat.Gif))
{
image.Save(ms, ImageFormat.Gif);
}
else if (format.Equals(ImageFormat.Icon))
{
image.Save(ms, ImageFormat.Icon);
}
byte[] buffer = new byte[ms.Length];
//Image.Save()会改变MemoryStream的Position需要重新Seek到Begin
ms.Seek(0, SeekOrigin.Begin);
ms.Read(buffer, 0, buffer.Length);
return buffer;
}
}
/// <summary>
/// Convert Byte[] to Image
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static Image BytesToImage(byte[] buffer)
{
MemoryStream ms = new MemoryStream(buffer);
Image image = System.Drawing.Image.FromStream(ms);
return image;
}
/// <summary>
/// Convert Byte[] to a picture and Store it in file
/// </summary>
/// <param name="fileName"></param>
/// <param name="buffer"></param>
/// <returns></returns>
public static string CreateImageFromBytes(string fileName, byte[] buffer)
{
string file = fileName;
Image image = BytesToImage(buffer);
ImageFormat format = image.RawFormat;
if (format.Equals(ImageFormat.Jpeg))
{
file += ".jpeg";
}
else if (format.Equals(ImageFormat.Png))
{
file += ".png";
}
else if (format.Equals(ImageFormat.Bmp))
{
file += ".bmp";
}
else if (format.Equals(ImageFormat.Gif))
{
file += ".gif";
}
else if (format.Equals(ImageFormat.Icon))
{
file += ".icon";
}
System.IO.FileInfo info = new System.IO.FileInfo(file);
System.IO.Directory.CreateDirectory(info.Directory.FullName);
File.WriteAllBytes(file, buffer);
return file;
}
}
}

View File

@@ -0,0 +1,57 @@
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace NetWorkHelper
{
public static class MD5Helper
{
public static string CretaeMD5(string fileName)
{
string hashStr = string.Empty;
try
{
FileStream fs = new FileStream(
fileName,
FileMode.Open,
FileAccess.Read,
FileShare.Read);
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] hash = md5.ComputeHash(fs);
hashStr = ByteArrayToHexString(hash);
fs.Close();
fs.Dispose();
}
catch (Exception ex)
{
throw ex;
}
return hashStr;
}
public static string CretaeMD5(Stream stream)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] hash = md5.ComputeHash(stream);
return ByteArrayToHexString(hash);
}
public static string CretaeMD5(byte[] buffer, int offset, int count)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] hash = md5.ComputeHash(buffer, offset, count);
return ByteArrayToHexString(hash);
}
private static string ByteArrayToHexString(byte[] values)
{
StringBuilder sb = new StringBuilder();
foreach (byte value in values)
{
sb.AppendFormat("{0:X2}", value);
}
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,582 @@
using NetWorkHelper.IBase;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace NetWorkHelper.Helper
{
public static class ReflectionHelper
{
#region
/// <summary>
/// GetType 通过完全限定的类型名来加载对应的类型。typeAndAssName如"NetWorkHelper.Filters.SourceFilter,NetWorkHelper"。
/// 如果为系统简单类型,则可以不带程序集名称。
/// </summary>
public static Type GetType(string typeAndAssName)
{
string[] names = typeAndAssName.Split(',');
if (names.Length < 2)
{
return Type.GetType(typeAndAssName);
}
return ReflectionHelper.GetType(names[0].Trim(), names[1].Trim());
}
/// <summary>
/// GetType 加载assemblyName程序集中的名为typeFullName的类型。assemblyName不用带扩展名如果目标类型在当前程序集中assemblyName传入null
/// </summary>
public static Type GetType(string typeFullName, string assemblyName)
{
if (assemblyName == null)
{
return Type.GetType(typeFullName);
}
//搜索当前域中已加载的程序集
Assembly[] asses = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly ass in asses)
{
string[] names = ass.FullName.Split(',');
if (names[0].Trim() == assemblyName.Trim())
{
return ass.GetType(typeFullName);
}
}
//加载目标程序集
Assembly tarAssem = Assembly.Load(assemblyName);
if (tarAssem != null)
{
return tarAssem.GetType(typeFullName);
}
return null;
}
#endregion
#region GetTypeFullName
public static string GetTypeFullName(Type t)
{
return t.FullName + "," + t.Assembly.FullName.Split(',')[0];
}
#endregion
#region LoadDerivedInstance
/// <summary>
/// LoadDerivedInstance 将程序集中所有继承自TBase的类型实例化
/// </summary>
/// <typeparam name="TBase">基础类型(或接口类型)</typeparam>
/// <param name="asm">目标程序集</param>
/// <returns>TBase实例列表</returns>
public static IList<TBase> LoadDerivedInstance<TBase>(Assembly asm)
{
IList<TBase> list = new List<TBase>();
Type supType = typeof(TBase);
foreach (Type t in asm.GetTypes())
{
if (supType.IsAssignableFrom(t) && (!t.IsAbstract) && (!t.IsInterface))
{
TBase instance = (TBase)Activator.CreateInstance(t);
list.Add(instance);
}
}
return list;
}
#endregion
#region LoadDerivedType
/// <summary>
/// LoadDerivedType 加载directorySearched目录下所有程序集中的所有派生自baseType的类型
/// </summary>
/// <typeparam name="baseType">基类(或接口)类型</typeparam>
/// <param name="directorySearched">搜索的目录</param>
/// <param name="searchChildFolder">是否搜索子目录中的程序集</param>
/// <param name="config">高级配置可以传入null采用默认配置</param>
/// <returns>所有从BaseType派生的类型列表</returns>
public static IList<Type> LoadDerivedType(Type baseType, string directorySearched, bool searchChildFolder, TypeLoadConfig config)
{
if (config == null)
{
config = new TypeLoadConfig();
}
IList<Type> derivedTypeList = new List<Type>();
if (searchChildFolder)
{
ReflectionHelper.LoadDerivedTypeInAllFolder(baseType, derivedTypeList, directorySearched, config);
}
else
{
ReflectionHelper.LoadDerivedTypeInOneFolder(baseType, derivedTypeList, directorySearched, config);
}
return derivedTypeList;
}
#region TypeLoadConfig
public class TypeLoadConfig
{
#region Ctor
public TypeLoadConfig() { }
public TypeLoadConfig(bool copyToMem, bool loadAbstract, string postfix)
{
this.copyToMemory = copyToMem;
this.loadAbstractType = loadAbstract;
this.targetFilePostfix = postfix;
}
#endregion
#region CopyToMemory
private bool copyToMemory = false;
/// <summary>
/// CopyToMem 是否将程序集拷贝到内存后加载
/// </summary>
public bool CopyToMemory
{
get { return copyToMemory; }
set { copyToMemory = value; }
}
#endregion
#region LoadAbstractType
private bool loadAbstractType = false;
/// <summary>
/// LoadAbstractType 是否加载抽象类型
/// </summary>
public bool LoadAbstractType
{
get { return loadAbstractType; }
set { loadAbstractType = value; }
}
#endregion
#region TargetFilePostfix
private string targetFilePostfix = ".dll";
/// <summary>
/// TargetFilePostfix 搜索的目标程序集的后缀名
/// </summary>
public string TargetFilePostfix
{
get { return targetFilePostfix; }
set { targetFilePostfix = value; }
}
#endregion
}
#endregion
#region LoadDerivedTypeInAllFolder
private static void LoadDerivedTypeInAllFolder(Type baseType, IList<Type> derivedTypeList, string folderPath, TypeLoadConfig config)
{
ReflectionHelper.LoadDerivedTypeInOneFolder(baseType, derivedTypeList, folderPath, config);
string[] folders = Directory.GetDirectories(folderPath);
if (folders != null)
{
foreach (string nextFolder in folders)
{
ReflectionHelper.LoadDerivedTypeInAllFolder(baseType, derivedTypeList, nextFolder, config);
}
}
}
#endregion
#region LoadDerivedTypeInOneFolder
private static void LoadDerivedTypeInOneFolder(Type baseType, IList<Type> derivedTypeList, string folderPath, TypeLoadConfig config)
{
string[] files = Directory.GetFiles(folderPath);
foreach (string file in files)
{
if (config.TargetFilePostfix != null)
{
if (!file.EndsWith(config.TargetFilePostfix))
{
continue;
}
}
Assembly asm = null;
#region Asm
try
{
if (config.CopyToMemory)
{
byte[] addinStream = FileHelper.ReadFileReturnBytes(file);
asm = Assembly.Load(addinStream);
}
else
{
asm = Assembly.LoadFrom(file);
}
}
catch (Exception ee)
{
ee = ee;
}
if (asm == null)
{
continue;
}
#endregion
Type[] types = asm.GetTypes();
foreach (Type t in types)
{
if (t.IsSubclassOf(baseType) || baseType.IsAssignableFrom(t))
{
bool canLoad = config.LoadAbstractType ? true : (!t.IsAbstract);
if (canLoad)
{
derivedTypeList.Add(t);
}
}
}
}
}
#endregion
#endregion
#region SetProperty
/// <summary>
/// SetProperty 如果list中的object具有指定的propertyName属性则设置该属性的值为proValue
/// </summary>
public static void SetProperty(IList<object> objs, string propertyName, object proValue)
{
object[] args = { proValue };
foreach (object target in objs)
{
ReflectionHelper.SetProperty(target, propertyName, proValue);
}
}
public static void SetProperty(object obj, string propertyName, object proValue)
{
ReflectionHelper.SetProperty(obj, propertyName, proValue, true);
}
/// <summary>
/// SetProperty 如果object具有指定的propertyName属性则设置该属性的值为proValue
/// </summary>
public static void SetProperty(object obj, string propertyName, object proValue, bool ignoreError)
{
Type t = obj.GetType();
PropertyInfo pro = t.GetProperty(propertyName);
if ((pro == null) || (!pro.CanWrite))
{
if (!ignoreError)
{
string msg = string.Format("The setter of property named '{0}' not found in '{1}'.", propertyName, t);
throw new Exception(msg);
}
return;
}
#region
try
{
proValue = TypeHelper.ChangeType(pro.PropertyType, proValue);
}
catch { }
#endregion
object[] args = { proValue };
t.InvokeMember(propertyName, BindingFlags.Public | BindingFlags.IgnoreCase |
BindingFlags.Instance | BindingFlags.SetProperty, null, obj, args);
}
#endregion
#region GetProperty
/// <summary>
/// GetProperty 根据指定的属性名获取目标对象该属性的值
/// </summary>
public static object GetProperty(object obj, string propertyName)
{
Type t = obj.GetType();
return t.InvokeMember(propertyName, BindingFlags.Default | BindingFlags.GetProperty, null, obj, null);
}
#endregion
#region GetFieldValue
/// <summary>
/// GetFieldValue 取得目标对象的指定field的值field可以是private
/// </summary>
public static object GetFieldValue(object obj, string fieldName)
{
Type t = obj.GetType();
FieldInfo field = t.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
if (field == null)
{
string msg = string.Format("The field named '{0}' not found in '{1}'.", fieldName, t);
throw new Exception(msg);
}
return field.GetValue(obj);
}
#endregion
#region SetFieldValue
/// <summary>
/// SetFieldValue 设置目标对象的指定field的值field可以是private
/// </summary>
public static void SetFieldValue(object obj, string fieldName, object val)
{
Type t = obj.GetType();
FieldInfo field = t.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetField | BindingFlags.Instance);
if (field == null)
{
string msg = string.Format("The field named '{0}' not found in '{1}'.", fieldName, t);
throw new Exception(msg);
}
field.SetValue(obj, val);
}
#endregion
#region CopyProperty
/// <summary>
/// CopyProperty 将source中的属性的值赋给target上同名的属性
/// 使用CopyProperty可以方便的实现拷贝构造函数
/// </summary>
public static void CopyProperty(object source, object target)
{
ReflectionHelper.CopyProperty(source, target, null);
}
/// <summary>
/// CopyProperty 将source中的属性的值赋给target上想匹配的属性匹配关系通过propertyMapItemList确定
/// </summary>
public static void CopyProperty(object source, object target, IList<MapItem> propertyMapItemList)
{
Type sourceType = source.GetType();
Type targetType = target.GetType();
PropertyInfo[] sourcePros = sourceType.GetProperties();
if (propertyMapItemList != null)
{
foreach (MapItem item in propertyMapItemList)
{
object val = ReflectionHelper.GetProperty(source, item.Source);
ReflectionHelper.SetProperty(target, item.Target, val);
}
}
else
{
foreach (PropertyInfo sourceProperty in sourcePros)
{
if (sourceProperty.CanRead)
{
object val = ReflectionHelper.GetProperty(source, sourceProperty.Name);
ReflectionHelper.SetProperty(target, sourceProperty.Name, val);
}
}
}
}
#endregion
#region GetAllMethodsSearchMethod
/// <summary>
/// GetAllMethods 获取接口的所有方法信息,包括继承的
/// </summary>
public static IList<MethodInfo> GetAllMethods(params Type[] interfaceTypes)
{
foreach (Type interfaceType in interfaceTypes)
{
if (!interfaceType.IsInterface)
{
throw new Exception("Target Type must be interface!");
}
}
IList<MethodInfo> list = new List<MethodInfo>();
foreach (Type interfaceType in interfaceTypes)
{
ReflectionHelper.DistillMethods(interfaceType, ref list);
}
return list;
}
private static void DistillMethods(Type interfaceType, ref IList<MethodInfo> methodList)
{
foreach (MethodInfo meth in interfaceType.GetMethods())
{
bool isExist = false;
foreach (MethodInfo temp in methodList)
{
if ((temp.Name == meth.Name) && (temp.ReturnType == meth.ReturnType))
{
ParameterInfo[] para1 = temp.GetParameters();
ParameterInfo[] para2 = meth.GetParameters();
if (para1.Length == para2.Length)
{
bool same = true;
for (int i = 0; i < para1.Length; i++)
{
if (para1[i].ParameterType != para2[i].ParameterType)
{
same = false;
}
}
if (same)
{
isExist = true;
break;
}
}
}
}
if (!isExist)
{
methodList.Add(meth);
}
}
foreach (Type superInterfaceType in interfaceType.GetInterfaces())
{
ReflectionHelper.DistillMethods(superInterfaceType, ref methodList);
}
}
/// <summary>
/// SearchGenericMethodInType 搜索指定类型定义的泛型方法,不包括继承的。
/// </summary>
public static MethodInfo SearchGenericMethodInType(Type originType, string methodName, Type[] argTypes)
{
foreach (MethodInfo method in originType.GetMethods())
{
if (method.ContainsGenericParameters && method.Name == methodName)
{
bool succeed = true;
ParameterInfo[] paras = method.GetParameters();
if (paras.Length == argTypes.Length)
{
for (int i = 0; i < paras.Length; i++)
{
if (!paras[i].ParameterType.IsGenericParameter) //跳过泛型参数
{
if (paras[i].ParameterType.IsGenericType) //如果参数本身就是泛型类型如IList<T>
{
if (paras[i].ParameterType.GetGenericTypeDefinition() != argTypes[i].GetGenericTypeDefinition())
{
succeed = false;
break;
}
}
else //普通类型的参数
{
if (paras[i].ParameterType != argTypes[i])
{
succeed = false;
break;
}
}
}
}
if (succeed)
{
return method;
}
}
}
}
return null;
}
/// <summary>
/// SearchMethod 包括被继承的所有方法,也包括泛型方法。
/// </summary>
public static MethodInfo SearchMethod(Type originType, string methodName, Type[] argTypes)
{
MethodInfo meth = originType.GetMethod(methodName, argTypes);
if (meth != null)
{
return meth;
}
meth = ReflectionHelper.SearchGenericMethodInType(originType, methodName, argTypes);
if (meth != null)
{
return meth;
}
//搜索基类
Type baseType = originType.BaseType;
if (baseType != null)
{
while (baseType != typeof(object))
{
MethodInfo target = baseType.GetMethod(methodName, argTypes);
if (target != null)
{
return target;
}
target = ReflectionHelper.SearchGenericMethodInType(baseType, methodName, argTypes);
if (target != null)
{
return target;
}
baseType = baseType.BaseType;
}
}
//搜索基接口
if (originType.GetInterfaces() != null)
{
IList<MethodInfo> list = ReflectionHelper.GetAllMethods(originType.GetInterfaces());
foreach (MethodInfo theMethod in list)
{
if (theMethod.Name != methodName)
{
continue;
}
ParameterInfo[] args = theMethod.GetParameters();
if (args.Length != argTypes.Length)
{
continue;
}
bool correctArgType = true;
for (int i = 0; i < args.Length; i++)
{
if (args[i].ParameterType != argTypes[i])
{
correctArgType = false;
break;
}
}
if (correctArgType)
{
return theMethod;
}
}
}
return null;
}
#endregion
#region GetFullMethodName
public static string GetMethodFullName(MethodInfo method)
{
return string.Format("{0}.{1}()", method.DeclaringType, method.Name);
}
#endregion
}
}

View File

@@ -0,0 +1,65 @@
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace NetWorkHelper
{
/// <summary>
/// 负责将对象序列化成byte[]数组
/// </summary>
public class SerHelper
{
/// <summary>
/// 将实体序列化成byte[]数组
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static byte[] Serialize(object obj)
{
// 1.0 实例化流的序列化帮助类
BinaryFormatter bf = new BinaryFormatter();
//2.0 定义内存流用来接收通过bf的Serialize方法将obj对象序列化成byte[]字节数组
byte[] res;
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, obj);
res = ms.ToArray();
}
return res;
}
/// <summary>
/// 根据byte[]字节数组反序列化成 对象实体
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static T Deserialize<T>(byte[] buffer)
{
// 1.0 实例化流的序列化帮助类
BinaryFormatter bf = new BinaryFormatter();
T obj;
using (MemoryStream ms = new MemoryStream(buffer))
{
obj = (T)bf.Deserialize(ms);
}
//bf.Deserialize(
return obj;
}
/// <summary>
/// 根据byte[]字节数组反序列化成 对象实体
/// </summary>
/// <param name="datas"></param>
/// <param name="index"></param>
/// <returns></returns>
public static object Deserialize(byte[] datas, int index)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream stream = new MemoryStream(datas, index, datas.Length - index);
object obj = bf.Deserialize(stream);
stream.Dispose();
return obj;
}
}
}

View File

@@ -0,0 +1,293 @@
using System;
namespace NetWorkHelper.Helper
{
public static class TypeHelper
{
#region IsSimpleType
/// <summary>
/// IsSimpleType 是否为简单类型数值、字符、字符串、日期、布尔、枚举、Type
/// </summary>
public static bool IsSimpleType(Type t)
{
if (TypeHelper.IsNumbericType(t))
{
return true;
}
if (t == typeof(char))
{
return true;
}
if (t == typeof(string))
{
return true;
}
if (t == typeof(bool))
{
return true;
}
if (t == typeof(DateTime))
{
return true;
}
if (t == typeof(Type))
{
return true;
}
if (t.IsEnum)
{
return true;
}
return false;
}
#endregion
#region IsNumbericType
public static bool IsNumbericType(Type destDataType)
{
if ((destDataType == typeof(int)) || (destDataType == typeof(uint)) || (destDataType == typeof(double))
|| (destDataType == typeof(short)) || (destDataType == typeof(ushort)) || (destDataType == typeof(decimal))
|| (destDataType == typeof(long)) || (destDataType == typeof(ulong)) || (destDataType == typeof(float))
|| (destDataType == typeof(byte)) || (destDataType == typeof(sbyte)))
{
return true;
}
return false;
}
#endregion
#region IsIntegerCompatibleType
public static bool IsIntegerCompatibleType(Type destDataType)
{
if ((destDataType == typeof(int)) || (destDataType == typeof(uint)) || (destDataType == typeof(short)) || (destDataType == typeof(ushort))
|| (destDataType == typeof(long)) || (destDataType == typeof(ulong)) || (destDataType == typeof(byte)) || (destDataType == typeof(sbyte)))
{
return true;
}
return false;
}
#endregion
#region GetClassSimpleName
/// <summary>
/// GetClassSimpleName 获取class的声明名称如 Person
/// </summary>
public static string GetClassSimpleName(Type t)
{
string[] parts = t.ToString().Split('.');
return parts[parts.Length - 1].ToString();
}
#endregion
#region IsFixLength
public static bool IsFixLength(Type destDataType)
{
if (TypeHelper.IsNumbericType(destDataType))
{
return true;
}
if (destDataType == typeof(byte[]))
{
return true;
}
if ((destDataType == typeof(DateTime)) || (destDataType == typeof(bool)))
{
return true;
}
return false;
}
#endregion
#region ChangeType
/// <summary>
/// ChangeType 对System.Convert.ChangeType进行了增强支持(0,1)到bool的转换字符串->枚举、int->枚举、字符串->Type
/// </summary>
public static object ChangeType(Type targetType, object val)
{
#region null
if (val == null)
{
return null;
}
#endregion
if (targetType.IsAssignableFrom(val.GetType()))
{
return val;
}
#region Same Type
if (targetType == val.GetType())
{
return val;
}
#endregion
#region bool 1,0
if (targetType == typeof(bool))
{
if (val.ToString() == "0")
{
return false;
}
if (val.ToString() == "1")
{
return true;
}
}
#endregion
#region Enum
if (targetType.IsEnum)
{
int intVal = 0;
bool suc = int.TryParse(val.ToString(), out intVal);
if (!suc)
{
return Enum.Parse(targetType, val.ToString());
}
else
{
return val;
}
}
#endregion
#region Type
if (targetType == typeof(Type))
{
return ReflectionHelper.GetType(val.ToString());
}
#endregion
if (targetType == typeof(IComparable))
{
return val;
}
//将double赋值给数值型的DataRow的字段是可以的但是通过反射赋值给object的非double的其它数值类型的属性却不行
return System.Convert.ChangeType(val, targetType);
}
#endregion
#region GetDefaultValue
public static object GetDefaultValue(Type destType)
{
if (TypeHelper.IsNumbericType(destType))
{
return 0;
}
if (destType == typeof(string))
{
return "";
}
if (destType == typeof(bool))
{
return false;
}
if (destType == typeof(DateTime))
{
return DateTime.Now;
}
if (destType == typeof(Guid))
{
return System.Guid.NewGuid();
}
if (destType == typeof(TimeSpan))
{
return System.TimeSpan.Zero;
}
return null;
}
#endregion
#region GetDefaultValueString
public static string GetDefaultValueString(Type destType)
{
if (TypeHelper.IsNumbericType(destType))
{
return "0";
}
if (destType == typeof(string))
{
return "\"\"";
}
if (destType == typeof(bool))
{
return "false";
}
if (destType == typeof(DateTime))
{
return "DateTime.Now";
}
if (destType == typeof(Guid))
{
return "System.Guid.NewGuid()";
}
if (destType == typeof(TimeSpan))
{
return "System.TimeSpan.Zero";
}
return "null";
}
#endregion
#region GetTypeRegularName
/// <summary>
/// GetTypeRegularName 获取类型的完全名称,如"ESBasic.Filters.SourceFilter,ESBasic"
/// </summary>
public static string GetTypeRegularName(Type destType)
{
string assName = destType.Assembly.FullName.Split(',')[0];
return string.Format("{0},{1}", destType.ToString(), assName);
}
public static string GetTypeRegularNameOf(object obj)
{
Type destType = obj.GetType();
return TypeHelper.GetTypeRegularName(destType);
}
#endregion
#region GetTypeByRegularName
/// <summary>
/// GetTypeByFullString 通过类型的完全名称获取类型regularName如"ESBasic.Filters.SourceFilter,ESBasic"
/// </summary>
public static Type GetTypeByRegularName(string regularName)
{
return ReflectionHelper.GetType(regularName);
}
#endregion
}
}

View File

@@ -0,0 +1,269 @@
/********************************************************************
* *
* * Copyright (C) 2013-2018 uiskin.cn
* * 作者: BinGoo QQ315567586
* * 请尊重作者劳动成果,请保留以上作者信息,禁止用于商业活动。
* *
* * 创建时间2014-08-05
* * 说明Windows帮助类
* *
********************************************************************/
using Microsoft.Win32;
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace NetWorkHelper.Helper
{
public class WindowsHelper
{
#region
/// <summary>
/// 开机自动启动,使用注册表
/// </summary>
/// <param name="started">是否开机自动启动</param>
/// <param name="name">取一个唯一的注册表Key名称</param>
/// <param name="path">启动程序的完整路径</param>
public static void RunWhenStart_usingReg(bool started, string name, string path)
{
RegistryKey HKLM = Registry.LocalMachine;
try
{
RegistryKey run = HKLM.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\");
if (run == null)
{
return;
}
if (started)
{
run.SetValue(name, path);
}
else
{
object val = run.GetValue(name);
if (val != null)
{
run.DeleteValue(name);
}
}
}
finally
{
HKLM.Close();
}
}
#endregion
#region MouseEvent /
/// <summary>
/// MouseEvent 模拟鼠标点击
/// </summary>
[DllImport("user32.dll", EntryPoint = "mouse_event")]
public static extern void MouseEvent(MouseEventFlag flags, int dx, int dy, uint data, UIntPtr extraInfo);
//在(34, 258)处点击鼠标
//SetCursorPos(34, 258);
//MouseEvent(MouseEventFlag.LeftDown, 0, 0, 0, UIntPtr.Zero);
//MouseEvent(MouseEventFlag.LeftUp, 0, 0, 0, UIntPtr.Zero);
/// <summary>
/// SetCursorPos 设置光标的绝对位置
/// </summary>
[DllImport("user32.dll")]
public static extern bool SetCursorPos(int x, int y);
/// <summary>
/// KeybdEvent 模拟键盘。已经过期。
/// </summary>
[DllImport("user32.dll", EntryPoint = "keybd_event")]
public static extern void KeybdEvent2(byte key, byte bScan, KeybdEventFlag flags, uint dwExtraInfo);
public static void KeybdEvent(byte key, byte bScan, KeybdEventFlag flags, uint dwExtraInfo)
{
INPUT input = new INPUT();
input.type = 1; //keyboard
input.ki.wVk = key;
input.ki.wScan = MapVirtualKey(key, 0);
input.ki.dwFlags = (int)flags;
SendInput(1, ref input, Marshal.SizeOf(input));
}
[DllImport("user32.dll")]
private static extern UInt32 SendInput(UInt32 nInputs, ref INPUT pInputs, int cbSize);
[DllImport("user32.dll")]
private static extern byte MapVirtualKey(byte wCode, int wMap);
#endregion
#region
/// <summary>
/// 根据扩展名获取系统图标。
/// </summary>
/// <param name="fileType">文件类型,使用扩展名表示,如".txt"</param>
public static Icon GetSystemIconByFileType(string fileType, bool isLarge)
{
if (isLarge)
{
return GetIcon(fileType, FILE_ATTRIBUTE.NORMAL, SHGFI.USEFILEATTRIBUTES | SHGFI.ICON | SHGFI.LARGEICON);
}
return GetIcon(fileType, FILE_ATTRIBUTE.NORMAL, SHGFI.USEFILEATTRIBUTES | SHGFI.ICON | SHGFI.SMALLICON);
}
private static Icon GetIcon(string path, FILE_ATTRIBUTE dwAttr, SHGFI dwFlag)
{
SHFILEINFO fi = new SHFILEINFO();
Icon ic = null;
int iTotal = (int)SHGetFileInfo(path, dwAttr, ref fi, 0, dwFlag);
ic = Icon.FromHandle(fi.hIcon);
return ic;
}
#region shell32函数
[DllImport("shell32", EntryPoint = "SHGetFileInfo", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SHGetFileInfo(string pszPath, FILE_ATTRIBUTE dwFileAttributes, ref SHFILEINFO sfi, int cbFileInfo, SHGFI uFlags);
// Contains information about a file object
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct SHFILEINFO
{
public IntPtr hIcon; //文件的图标句柄
public IntPtr iIcon; //图标的系统索引号
public uint dwAttributes; //文件的属性值
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName; //文件的显示名
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName; //文件的类型名
};
// Flags that specify the file information to retrieve with SHGetFileInfo
[Flags]
public enum SHGFI : uint
{
ADDOVERLAYS = 0x20,
ATTR_SPECIFIED = 0x20000,
ATTRIBUTES = 0x800, //获得属性
DISPLAYNAME = 0x200, //获得显示名
EXETYPE = 0x2000,
ICON = 0x100, //获得图标
ICONLOCATION = 0x1000,
LARGEICON = 0, //获得大图标
LINKOVERLAY = 0x8000,
OPENICON = 2,
OVERLAYINDEX = 0x40,
PIDL = 8,
SELECTED = 0x10000,
SHELLICONSIZE = 4,
SMALLICON = 1, //获得小图标
SYSICONINDEX = 0x4000,
TYPENAME = 0x400, //获得类型名
USEFILEATTRIBUTES = 0x10
}
// Flags that specify the file information to retrieve with SHGetFileInfo
[Flags]
public enum FILE_ATTRIBUTE
{
READONLY = 0x00000001,
HIDDEN = 0x00000002,
SYSTEM = 0x00000004,
DIRECTORY = 0x00000010,
ARCHIVE = 0x00000020,
DEVICE = 0x00000040,
NORMAL = 0x00000080,
TEMPORARY = 0x00000100,
SPARSE_FILE = 0x00000200,
REPARSE_POINT = 0x00000400,
COMPRESSED = 0x00000800,
OFFLINE = 0x00001000,
NOT_CONTENT_INDEXED = 0x00002000,
ENCRYPTED = 0x00004000
}
#endregion
#endregion
#region TopLevel在最前
[DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
private static extern bool SetActiveWindow(IntPtr hWnd);
/// <summary>
/// 设置目标窗体为活动窗体将其TopLevel在最前。
/// </summary>
public static void SetForegroundWindow(Form window)
{
SetActiveWindow(window.Handle);
}
#endregion
}
#region MouseEventFlag ,KeybdEventFlag
/// <summary>
/// 模拟鼠标点击的相关标志 。
/// </summary>
[Flags]
public enum MouseEventFlag : uint
{
Move = 0x0001,
LeftDown = 0x0002,
LeftUp = 0x0004,
RightDown = 0x0008,
RightUp = 0x0010,
MiddleDown = 0x0020,
MiddleUp = 0x0040,
XDown = 0x0080,
XUp = 0x0100,
Wheel = 0x0800,
VirtualDesk = 0x4000,
Absolute = 0x8000 //绝对坐标
}
/// <summary>
/// 模拟键盘点击的相关标志 。
/// </summary>
[Flags]
public enum KeybdEventFlag : uint
{
Down = 0,
Up = 0x0002
}
#endregion
[StructLayout(LayoutKind.Explicit)]
public struct INPUT
{
[FieldOffset(0)]
public Int32 type;
[FieldOffset(4)]
public KEYBDINPUT ki;
[FieldOffset(4)]
public MOUSEINPUT mi;
[FieldOffset(4)]
public HARDWAREINPUT hi;
}
[StructLayout(LayoutKind.Sequential)]
public struct MOUSEINPUT
{
public Int32 dx;
public Int32 dy;
public Int32 mouseData;
public Int32 dwFlags;
public Int32 time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
public struct KEYBDINPUT
{
public Int16 wVk;
public Int16 wScan;
public Int32 dwFlags;
public Int32 time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
public struct HARDWAREINPUT
{
public Int32 uMsg;
public Int16 wParamL;
public Int16 wParamH;
}
}

View File

@@ -0,0 +1,166 @@
/********************************************************************
* *
* * Copyright (C) 2013-2018 uiskin.cn
* * 作者: BinGoo QQ315567586
* * 请尊重作者劳动成果,请保留以上作者信息,禁止用于商业活动。
* *
* * 创建时间2014-08-05
* * 说明实体类与XML互转帮助类
* *
********************************************************************/
using System;
using System.IO;
using System.Xml.Serialization;
namespace NetWorkHelper.Helper
{
/// <summary>
/// 实体类与XML互转多用于保存配置文件
/// </summary>
public class XmlHelper
{
#region
/// <summary>
/// 反序列化返回实体类
/// </summary>
/// <param name="type">类型</param>
/// <param name="xml">XML字符串</param>
/// <returns>返回实体类</returns>
public static object Deserialize(Type type, string xml)
{
try
{
using (StringReader sr = new StringReader(xml))
{
XmlSerializer xmldes = new XmlSerializer(type);
return xmldes.Deserialize(sr);
}
}
catch (Exception e)
{
return null;
}
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="type"></param>
/// <param name="xml"></param>
/// <returns></returns>
public static object Deserialize(Type type, Stream stream)
{
XmlSerializer xmldes = new XmlSerializer(type);
return xmldes.Deserialize(stream);
}
#endregion
#region
/// <summary>
/// 序列化返回XML字符串
/// </summary>
/// <param name="type">类型</param>
/// <param name="obj">对象</param>
/// <returns>返回XML字符串</returns>
public static string Serializer(Type type, object obj)
{
MemoryStream Stream = new MemoryStream();
XmlSerializer xml = new XmlSerializer(type);
try
{
//序列化对象
xml.Serialize(Stream, obj);
}
catch (InvalidOperationException)
{
throw;
}
Stream.Position = 0;
StreamReader sr = new StreamReader(Stream);
string str = sr.ReadToEnd();
sr.Dispose();
Stream.Dispose();
return str;
}
#endregion
#region XML字符串文件
/// <summary>
/// 写XML字符串文件
/// </summary>
/// <param name="datafilePath"></param>
/// <param name="dataFileName"></param>
/// <param name="message"></param>
public static void WriteXmlData(string datafilePath, string dataFileName, string message)
{
//DirectoryInfo path=new DirectoryInfo(DataFileName);
//如果数据文件目录不存在,则创建
if (!Directory.Exists(datafilePath))
{
Directory.CreateDirectory(datafilePath);
}
FileInfo finfo = new FileInfo(datafilePath + dataFileName);
try
{
using (FileStream fs = new FileStream(datafilePath + dataFileName, FileMode.Create))
{
using (StreamWriter strwriter = new StreamWriter(fs))
{
try
{
strwriter.WriteLine(message);
strwriter.Flush();
}
catch (Exception ex)
{
Console.WriteLine(string.Format("数据文件写入失败信息:{0},行号{1}", ex.Message, ex.StackTrace));
}
}
}
}
catch (Exception ee)
{
Console.WriteLine(string.Format("数据文件没有打开,详细信息如下:{0}", ee.Message));
}
}
#endregion
#region XML文件
/// <summary>
/// 读取XML文件
/// </summary>
/// <param name="fileName">文件名(包含路径)</param>
/// <returns>返回文件字符串</returns>
public static string ReadXmlFile(string fileName)
{
//异常检测开始
try
{
string fileContent = "";
using (var reader = new StreamReader(fileName))
{
fileContent = reader.ReadToEnd();
}
return fileContent;
}
catch
{
//抛出异常
return "";
}
//异常检测结束
}
#endregion
}
}