风痕之月 - Helper
type: channel
link: https://www.helj.top/index.php/category/Helper/
items: EmailHelper
items: FTPHelper
items: SqliteHelper
items: LinqHelper
items: LogHelper
items: XMLHelper
items: NPOIHelper
items: EnumHelper
items: ZipHelper
items: EncryptionHelper

EmailHelper
type: item
date: 2018-09-30T15:46:36+08:00
description: EmailHelperusing System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Mail; using System.Text; namespace Helper { /// /// Author : yenange /// Date : 2014-02-26 /// Description : 邮件发送辅助类 /// public class EmailHelper { #region [ 属性(发送Email相关) ] private string _SmtpHost = string.Empty; private int _SmtpPort = -1; private string _FromEmailAddress = string.Empty; private string _FormEmailPassword = string.Empty; /// /// smtp 服务器 /// public string SmtpHost { get { if (string.IsNullOrEmpty(_SmtpHost)) { _SmtpHost = ConfigurationManager.AppSettings["SmtpHost"]; } return _SmtpHost; } } /// /// smtp 服务器端口 默认为25 /// public int SmtpPort { get { if (_SmtpPort == -1) { if (!int.TryParse(ConfigurationManager.AppSettings["SmtpPort"], out _SmtpPort)) { _SmtpPort = 25; } } return _SmtpPort; } } /// /// 发送者 Eamil 地址 /// public string FromEmailAddress { get { if (string.IsNullOrEmpty(_FromEmailAddress)) { _FromEmailAddress = ConfigurationManager.AppSettings["FromEmailAddress"]; } return _FromEmailAddress; } } /// /// 发送者 Eamil 密码 /// public string FormEmailPassword { get { if (string.IsNullOrEmpty(_FormEmailPassword)) { _FormEmailPassword = ConfigurationManager.AppSettings["FormEmailPassword"]; } return _FormEmailPassword; } } #endregion #region [ 属性(邮件相关) ] /// /// 收件人 Email 列表，多个邮件地址之间用 半角逗号 分开 /// public string ToList { get; set; } /// /// 邮件的抄送者，支持群发，多个邮件地址之间用 半角逗号 分开 /// public string CCList { get; set; } /// /// 邮件的密送者，支持群发，多个邮件地址之间用 半角逗号 分开 /// public string BccList { get; set; } /// /// 邮件标题 /// public string Subject { get; set; } /// /// 邮件正文 /// public string Body { get; set; } private bool _IsBodyHtml = true; /// /// 邮件正文是否为Html格式 /// public bool IsBodyHtml { get { return _IsBodyHtml; } set { _IsBodyHtml = value; } } /// /// 附件列表 /// public List<Attachment> AttachmentList { get; set; } #endregion #region [ 构造函数 ] /// /// 构造函数 (body默认为html格式) /// /// 收件人列表 /// 邮件标题 /// 邮件正文 public EmailHelper(string toLis…

FTPHelper
type: item
date: 2018-09-30T15:45:57+08:00
description: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; namespace Helper { public class FTPHelper { /// /// FTP请求对象 /// FtpWebRequest request = null; /// /// FTP响应对象 /// FtpWebResponse response = null; /// /// FTP服务器地址 /// public string ftpURI { get; private set; } /// /// FTP服务器IP /// public string ftpServerIP { get; private set; } /// /// FTP服务器默认目录 /// public string ftpRemotePath { get; private set; } /// /// FTP服务器登录用户名 /// public string ftpUserID { get; private set; } /// /// FTP服务器登录密码 /// public string ftpPassword { get; private set; } /// /// 初始化 /// /// FTP连接地址 /// 指定FTP连接成功后的当前目录, 如果不指定即默认为根目录 /// 用户名 /// 密码 public FTPHelper(string ftpServerIP, string ftpRemotePath, string ftpUserID, string ftpPassword) { this.ftpServerIP = ftpServerIP; this.ftpRemotePath = ftpRemotePath; this.ftpUserID = ftpUserID; this.ftpPassword = ftpPassword; this.ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/"; } ~FTPHelper() { if (response != null) { response.Close(); response = null; } if (request != null) { request.Abort(); request = null; } } /// /// 建立FTP链接,返回响应对象 /// /// FTP地址 /// 操作命令 /// <returns></returns> private FtpWebResponse Open(Uri uri, string ftpMethod) { request = (FtpWebRequest)FtpWebRequest.Create(uri); request.Method = ftpMethod; request.UseBinary = true; request.KeepAlive = false; request.Credentials = new NetworkCredential(this.ftpUserID, this.ftpPassword); return (FtpWebResponse)request.GetResponse(); } /// /// 建立FTP链接,返回请求对象 /// /// FTP地址 /// 操作命令 private FtpWebRequest OpenRequest(Uri uri, string ftpMethod) { request = (FtpWebRequest)WebRequest.Create(uri); request.Method = ftpMethod; request.UseBinary = true; request.KeepAlive = false; request.Credentials = new NetworkCredential(this.ftpUserID, this.ftpPassword); return request; } /// /// 验证登录用户是否合法 /// /// ftp路径 /// ftp用户名 /// ftp密码 /// <returns></returns> public bool CheckFtp() { bool res = false; try { request = (FtpWebRequest)Ftp…

SqliteHelper
type: item
date: 2018-09-30T15:45:28+08:00
description: packageInstall-Package System.Data.SQLite.EF6Config<connectionStrings> <add name="DB_HES" connectionString="Data Source=|DataDirectory|App_Data\DB_HES.db;Version=3;UseUnicode=true;characterEncoding=UTF-8;" providerName="System.Data.SQLite.EF6" /> </connectionStrings>SqliteHelperusing System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SQLite; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Xml; namespace HES.AddAdmin { /// /// 对SQLite操作的类 /// 引用：System.Data.SQLite.dll【版本：3.6.23.1（原始文件名：SQlite3.DLL）】 /// public class SQLiteHelper { /// /// 所有成员函数都是静态的，构造函数定义为私有 /// private SQLiteHelper() { } /// /// 连接字符串 /// public static string ConnectionString {//"Data Source=Test.db3;Pooling=true;FailIfMissing=false"; get { ////(AppSettings节点下的"SQLiteConnectionString") string text = ConfigurationManager.ConnectionStrings["SQLiteConnectionString"].ConnectionString; //string str2 = ConfigurationManager.AppSettings["IsEncrypt"]; //if (str2 == "true") //{ // text = DesEncrypt.Decrypt(text); //} return text; } } private static SQLiteConnection _Conn = null; /// /// 连接对象 /// public static SQLiteConnection Conn { get { if (_Conn == null) _Conn = new SQLiteConnection(ConnectionString); return SQLiteHelper._Conn; } set { SQLiteHelper._Conn = value; } } #region CreateCommand(commandText,SQLiteParameter[]) /// /// 创建命令 /// /// 连接 /// 语句 /// 语句参数. /// <returns>SQLite Command</returns> public static SQLiteCommand CreateCommand(string commandText, params SQLiteParameter[] commandParameters) { SQLiteCommand cmd = new SQLiteCommand(commandText, Conn); if (commandParameters.Length > 0) { foreach (SQLiteParameter parm in commandParameters) cmd.Parameters.Add(parm); } return cmd; } #endregion #region CreateParameter(parameterName,parameterType,parameterValue) /// /// 创建参数 /// /// 参数名 /// 参数类型 /// 参数值 /// <returns>返回创建的参数</returns> public static SQLiteParamet…

LinqHelper
type: item
date: 2018-09-30T15:44:20+08:00
description: using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Helper { /// /// 查询语句帮助类 /// public static class LinqHelper { /// /// 动态排序 /// /// <typeparam name="T">实体类型</typeparam> /// 数据源 /// 排序字段 /// 排序方式 /// <returns></returns> public static IQueryable<T> DataSorting<T>(IQueryable<T> source, string sortExpression, string sortDirection) { string sortingDir = string.Empty; if (sortDirection.ToUpper().Trim() == "ASC") return source.OrderBy(a => typeof(T).GetProperty(sortExpression).GetValue(a, null)); else return source.OrderByDescending(a => typeof(T).GetProperty(sortExpression).GetValue(a, null)); } /// /// 动态排序旧方法 /// /// <typeparam name="T">实体类型</typeparam> /// 数据源 /// 排序字段 /// 排序方式 /// <returns></returns> public static IQueryable<T> DataSorting1<T>(IQueryable<T> source, string sortExpression, string sortDirection) { string sortingDir = string.Empty; if (sortDirection.ToUpper().Trim() == "ASC") sortingDir = "OrderBy"; else if (sortDirection.ToUpper().Trim() == "DESC") sortingDir = "OrderByDescending"; ParameterExpression param = Expression.Parameter(typeof(T), sortExpression); PropertyInfo pi = typeof(T).GetProperty(sortExpression); Type[] types = new Type[2]; types[0] = typeof(T); types[1] = pi.PropertyType; Expression expr = Expression.Call(typeof(Queryable), sortingDir, types, source.Expression, Expression.Lambda(Expression.Property(param, sortExpression), param)); IQueryable<T> query = source.AsQueryable().Provider.CreateQuery<T>(expr); return query; } /// /// 分页 /// /// <typeparam name="T">实体类型</typeparam> /// 数据源 /// 分页页码从第一页开始 /// 页码 /// <returns></returns> public static IQueryable<T> DataPaging<T>(IQueryable<T> source, int pageIndex, int pageSize) { return source.Skip((pageIndex-1) * pageSize).Take(pageSize); } /// /// 排序并分页 /// /// <typeparam name="T">实体类型</typeparam> /// 数据源 /// 排序字段 /// 排序方式 /// 分页页码从第一页开始 /// 页码 /// <returns></retu…

LogHelper
type: item
date: 2018-09-30T15:43:14+08:00
description: public enum LogType { Overall, } public class LogHelper { public static string LogPath { get { return AppDomain.CurrentDomain.BaseDirectory+@"\log"; } } public enum LogLevel { Info, Error } public static void Info(string message, LogType logType = LogType.Overall) { if (string.IsNullOrEmpty(message)) return; var path = string.Format(@"\{0}\", logType.ToString()); WriteLog(path, "", message); } public static void Error(string message, LogType logType = LogType.Overall) { if (string.IsNullOrEmpty(message)) return; var path = string.Format(@"\{0}\", logType.ToString()); WriteLog(path, "Error ", message); } public static void Error(Exception e, LogType logType = LogType.Overall) { if (e == null) return; var path = string.Format(@"\{0}\", logType.ToString()); WriteLog(path, "Error ", e.Message); } private static void WriteLog(string path, string prefix, string message) { path = LogPath + path; var fileName = string.Format("{0}{1}.log", prefix, DateTime.Now.ToString("yyyyMMdd")); if (!Directory.Exists(path)) Directory.CreateDirectory(path); using (FileStream fs = new FileStream(path + fileName, FileMode.Append, FileAccess.Write, FileShare.Write, 1024, FileOptions.Asynchronous)) { byte[] buffer = System.Text.Encoding.UTF8.GetBytes(DateTime.Now.ToString("HH:mm:ss") + " " + message + "\r\n"); IAsyncResult writeResult = fs.BeginWrite(buffer, 0, buffer.Length, (asyncResult) => { var fStream = (FileStream)asyncResult.AsyncState; fStream.EndWrite(asyncResult); }, fs); fs.Close(); } } }

XMLHelper
type: item
date: 2018-09-30T15:42:00+08:00
description: using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; namespace HesPis.Helper { public static class XmlHelper { private static string SettingPath { get { return AppDomain.CurrentDomain.BaseDirectory + @"\Config"; } } #region Fields and Properties public enum XmlType { File, String } #endregion #region Methods /// /// 创建XML文档 /// /// 根节点名称 /// 根节点的一个属性值 /// <returns></returns> public static XmlDocument CreateXmlDocument(string name, string type) { /************************************************** * .net中调用方法：写入文件中,则： *document = XmlOperate.CreateXmlDocument("sex", "sexy"); *document.Save("c:/bookstore.xml"); ************************************************/ XmlDocument xmlDocument; try { xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<" + name + "/>"); var rootElement = xmlDocument.DocumentElement; rootElement?.SetAttribute("type", type); } catch (Exception exception) { throw exception; } return xmlDocument; } /// /// 删除数据 /// /// 路径 /// 节点 /// 属性名，非空时删除该节点属性值，否则删除节点值 /// <returns></returns> public static void Delete(string path, string node, string attribute) { /************************************************** * 使用示列: * XmlHelper.Delete(path, "/Node", "") * XmlHelper.Delete(path, "/Node", "Attribute") ************************************************/ try { var xmlDocument = new XmlDocument(); xmlDocument.Load(path); var selectSingleNode = xmlDocument.SelectSingleNode(node); var xmlElement = (XmlElement)selectSingleNode; if (attribute.Equals("")) selectSingleNode?.ParentNode?.RemoveChild(selectSingleNode); else xmlElement?.RemoveAttribute(attribute); xmlDocument.Save(path); } catch (Exception exception) { throw exception; } } /// /// 读取XML资源到DataSet中 /// /// XML资源，文件为路径，否则为XML字符串 /// XML资源类型 /// <returns>DataSet</returns> public static DataSet GetDataSet(string source, XmlType xmlType) {…

NPOIHelper
type: item
date: 2018-09-30T15:40:00+08:00
description: packageInstall-Package NPOINPOIHelperusing NPOI.HPSF; using NPOI.HSSF.UserModel; using NPOI.SS.Formula.Eval; using NPOI.SS.UserModel; using NPOI.SS.Util; using NPOI.XSSF.UserModel; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Web; namespace Helper { /// /// NPOIHelper /// public class NPOIHelper { /// /// 公司 /// public static string Company="NPOI"; /// /// 作者 /// public static string Author = "作者"; /// /// 创建程序信息 /// public static string ApplicationName = "创建程序信息"; /// /// 最后保存者信息 /// public static string LastAuthor = "最后保存者信息"; /// /// 作者信息 /// public static string Comments = "作者信息"; /// /// 标题信息 /// public static string Title = "标题信息"; /// /// 主题信息 /// public static string Subject = "主题信息"; /// /// 创建Excel /// /// <returns></returns> public static HSSFWorkbook CreateExcel() { HSSFWorkbook workbook = new HSSFWorkbook(); #region 右击文件 属性信息 DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); dsi.Company = Company; workbook.DocumentSummaryInformation = dsi; SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); si.Author = Author; //填加xls文件作者信息 si.ApplicationName = ApplicationName; //填加xls文件创建程序信息 si.LastAuthor = LastAuthor; //填加xls文件最后保存者信息 si.Comments = Comments; //填加xls文件作者信息 si.Title = Title; //填加xls文件标题信息 si.Subject = Subject;//填加文件主题信息 si.CreateDateTime = DateTime.Now; workbook.SummaryInformation = si; #endregion return workbook; } #region 从datatable中将数据导出到excel /// /// DataTable导出到Excel的MemoryStream /// /// 源DataTable /// 表头文本 static MemoryStream ExportDT(DataTable dtSource, string strHeaderText) { HSSFWorkbook workbook = CreateExcel(); HSSFSheet sheet = workbook.CreateSheet() as HSSFSheet; HSSFCellStyle dateStyle = workbook.CreateCellStyle() as HSSFCellStyle; HSSFDataFormat format = workbook.CreateDataFormat() as HSSFDataFormat; …

EnumHelper
type: item
date: 2018-09-30T15:32:22+08:00
description: using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Web; using System.Web.Mvc; namespace Helper { public static class EnumHelper { #region Field private static ConcurrentDictionary<Type, Dictionary<int, string>> enumDisplayValueDict = new ConcurrentDictionary<Type, Dictionary<int, string>>(); private static ConcurrentDictionary<Type, Dictionary<string, int>> enumValueDisplayDict = new ConcurrentDictionary<Type, Dictionary<string, int>>(); private static ConcurrentDictionary<Type, Dictionary<int, string>> enumNameValueDict = new ConcurrentDictionary<Type, Dictionary<int, string>>(); private static ConcurrentDictionary<Type, Dictionary<string, int>> enumValueNameDict = new ConcurrentDictionary<Type, Dictionary<string, int>>(); private static ConcurrentDictionary<Type, Dictionary<int, Tuple<string, int>>> enumSeqDisplayValueDict = new ConcurrentDictionary<Type, Dictionary<int, Tuple<string, int>>>(); private static ConcurrentDictionary<string, Type> enumTypeDict = null; #endregion #region Method /// /// 获取枚举对象Key与显示名称的字典 /// /// /// <returns></returns> public static Dictionary<int, string> GetEnumDictionary(Type enumType) { if (!enumType.IsEnum) throw new Exception("给定的类型不是枚举类型"); Dictionary<int, string> names = enumNameValueDict.ContainsKey(enumType) ? enumNameValueDict[enumType] : new Dictionary<int, string>(); if (names.Count == 0) { names = GetEnumDictionaryItems(enumType); enumNameValueDict[enumType] = names; } return names; } private static Dictionary<int, string> GetEnumDictionaryItems(Type enumType) { FieldInfo[] enumItems = enumType.GetFields(BindingFlags.Public | BindingFlags.Static); Dictionary<int, string> names = new Dictionary<int, string>(enumItems.Length); foreach (FieldInfo enumItem in enumItems) { int intValue = (int)enumItem.GetValue(enumType); names[intValue] = enumItem.Name; } return names; } /…

ZipHelper
type: item
date: 2018-09-30T15:31:20+08:00
description: Packageusing System.IO.Compression; using System.IO.Compression.FileSystem;实例System.IO.Compression.ZipFile.CreateFromDirectory(@"C:\Users\Helj\Desktop\安装包\配置文件", @"C:\Users\Helj\Desktop\安装包\a.zip"); System.IO.Compression.ZipFile.ExtractToDirectory( @"C:\Users\Helj\Desktop\安装包\a.zip",@"C:\Users\Helj\Desktop\安装包\配置文件");

EncryptionHelper
type: item
date: 2018-09-30T15:29:16+08:00
description: AESusing System; using System.Security.Cryptography; using System.Text; namespace Helper.Encryption { /// /// 加密 /// public class AES { /// /// DES加密字符串 /// /// 待加密的字符串 /// 加密密钥,要求为8位 /// <returns>加密成功返回加密后的字符串,失败返回源串</returns> public static string AESEncrypt(string encryptString, string encryptKey) { try { if (string.IsNullOrEmpty(encryptString)) return null; Byte[] toEncryptArray = Encoding.UTF8.GetBytes(encryptString); System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged { Key = Encoding.UTF8.GetBytes(encryptKey), Mode = System.Security.Cryptography.CipherMode.ECB, Padding = System.Security.Cryptography.PaddingMode.PKCS7 }; System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } catch (Exception ex) { return ""; } } /// /// DES解密字符串 /// /// 待解密的字符串 /// 解密密钥,要求为8位,和加密密钥相同 /// <returns>解密成功返回解密后的字符串,失败返源串</returns> public static string AESDecrypt(string decryptString, string decryptKey) { try { if (string.IsNullOrEmpty(decryptString)) return null; Byte[] toEncryptArray = Convert.FromBase64String(decryptString); System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged { Key = Encoding.UTF8.GetBytes(decryptKey), Mode = System.Security.Cryptography.CipherMode.ECB, Padding = System.Security.Cryptography.PaddingMode.PKCS7 }; System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Encoding.UTF8.GetString(resultArray); } catch (Exception ex) { return ""; } } } } DESusing System; using System.IO; using System.Security.Cryptography; using System.Text; namespace Helper.Encryption { public class DES { /// /// 32位Key值： /// private static byte[] DESKey = new byte[] { 0x03, 0x0B, 0x…