转自与网络
1 /// <summary> 2 /// web.config操作类 3 /// </summary> 4 public sealed class ConfigHelper 5 { 6 /// <summary> 7 /// 得到AppSettings中的配置字符串信息 8 /// </summary> 9 /// <param name="key"></param> 10 /// <returns></returns> 11 public static string GetConfigString(string key) 12 { 13 object objModel = ConfigurationManager.AppSettings[key]; 14 return objModel.ToString(); 15 } 16 17 /// <summary> 18 /// 得到AppSettings中的配置Bool信息 19 /// </summary> 20 /// <param name="key"></param> 21 /// <returns></returns> 22 public static bool GetConfigBool(string key) 23 { 24 bool result = false; 25 string cfgVal = GetConfigString(key); 26 if (!string.IsNullOrEmpty(cfgVal)) 27 { 28 result = bool.Parse(cfgVal); 29 } 30 return result; 31 } 32 /// <summary> 33 /// 得到AppSettings中的配置Decimal信息 34 /// </summary> 35 /// <param name="key"></param> 36 /// <returns></returns> 37 public static decimal GetConfigDecimal(string key) 38 { 39 decimal result = 0; 40 string cfgVal = GetConfigString(key); 41 if (!string.IsNullOrEmpty(cfgVal)) 42 { 43 result = decimal.Parse(cfgVal); 44 } 45 return result; 46 } 47 /// <summary> 48 /// 得到AppSettings中的配置int信息 49 /// </summary> 50 /// <param name="key"></param> 51 /// <returns></returns> 52 public static int GetConfigInt(string key) 53 { 54 int result = 0; 55 string cfgVal = GetConfigString(key); 56 if (!string.IsNullOrEmpty(cfgVal)) 57 { 58 result = int.Parse(cfgVal); 59 } 60 61 return result; 62 } 63 }
ConfigHelper
1 /// <summary> 2 /// GZip压缩 3 /// </summary> 4 public class GZip 5 { 6 /// <summary> 7 /// 压缩 8 /// </summary> 9 /// <param name="text">文本</param> 10 public static string Compress(string text) 11 { 12 if (String.IsNullOrEmpty(text)) 13 return string.Empty; 14 byte[] buffer = Encoding.UTF8.GetBytes(text); 15 return Convert.ToBase64String(Compress(buffer)); 16 } 17 18 /// <summary> 19 /// 解压缩 20 /// </summary> 21 /// <param name="text">文本</param> 22 public static string Decompress(string text) 23 { 24 if (String.IsNullOrEmpty(text)) 25 return string.Empty; 26 byte[] buffer = Convert.FromBase64String(text); 27 using (var ms = new MemoryStream(buffer)) 28 { 29 using (var zip = new GZipStream(ms, CompressionMode.Decompress)) 30 { 31 using (var reader = new StreamReader(zip)) 32 { 33 return reader.ReadToEnd(); 34 } 35 } 36 } 37 } 38 39 /// <summary> 40 /// 压缩 41 /// </summary> 42 /// <param name="buffer">字节流</param> 43 public static byte[] Compress(byte[] buffer) 44 { 45 if (buffer == null) 46 return null; 47 using (var ms = new MemoryStream()) 48 { 49 using (var zip = new GZipStream(ms, CompressionMode.Compress, true)) 50 { 51 zip.Write(buffer, 0, buffer.Length); 52 } 53 return ms.ToArray(); 54 } 55 } 56 57 /// <summary> 58 /// 解压缩 59 /// </summary> 60 /// <param name="buffer">字节流</param> 61 public static byte[] Decompress(byte[] buffer) 62 { 63 if (buffer == null) 64 return null; 65 return Decompress(new MemoryStream(buffer)); 66 } 67 68 /// <summary> 69 /// 压缩 70 /// </summary> 71 /// <param name="stream">流</param> 72 public static byte[] Compress(Stream stream) 73 { 74 if (stream == null || stream.Length == 0) 75 return null; 76 return Compress(StreamToBytes(stream)); 77 } 78 79 /// <summary> 80 /// 解压缩 81 /// </summary> 82 /// <param name="stream">流</param> 83 public static byte[] Decompress(Stream stream) 84 { 85 if (stream == null || stream.Length == 0) 86 return null; 87 using (var zip = new GZipStream(stream, CompressionMode.Decompress)) 88 { 89 using (var reader = new StreamReader(zip)) 90 { 91 return Encoding.UTF8.GetBytes(reader.ReadToEnd()); 92 } 93 } 94 } 95 /// <summary> 96 /// 流转换为字节流 97 /// </summary> 98 /// <param name="stream">流</param> 99 public static byte[] StreamToBytes(Stream stream) 100 { 101 stream.Seek(0, SeekOrigin.Begin); 102 var buffer = new byte[stream.Length]; 103 stream.Read(buffer, 0, buffer.Length); 104 return buffer; 105 } 106 }
GZip压缩
1 /// <summary> 2 /// Cookie相关操作类 3 /// </summary> 4 public class CookieHelper 5 { 6 /// <summary> 7 /// 清除指定Cookie 8 /// </summary> 9 /// <param name="cookiename">cookiename</param> 10 public static void ClearCookie(string cookiename) 11 { 12 HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiename]; 13 if (cookie == null) return; 14 cookie.Expires = DateTime.Now.AddYears(-3); 15 HttpContext.Current.Response.Cookies.Add(cookie); 16 } 17 /// <summary> 18 /// 获取指定Cookie值 19 /// </summary> 20 /// <param name="cookiename">cookiename</param> 21 /// <returns></returns> 22 public static string GetCookieValue(string cookiename) 23 { 24 HttpCookie cookie = HttpContext.Current.Request.Cookies[cookiename]; 25 string str = string.Empty; 26 if (cookie != null) 27 { 28 str = cookie.Value; 29 } 30 return str; 31 } 32 /// <summary> 33 /// 添加一个Cookie(24小时过期) 34 /// </summary> 35 /// <param name="cookiename"></param> 36 /// <param name="cookievalue"></param> 37 public static void SetCookie(string cookiename, string cookievalue) 38 { 39 SetCookie(cookiename, cookievalue, DateTime.Now.AddDays(1.0)); 40 } 41 /// <summary> 42 /// 添加一个Cookie 43 /// </summary> 44 /// <param name="cookiename">cookie名</param> 45 /// <param name="cookievalue">cookie值</param> 46 /// <param name="expireTime">过期时间 expireTime</param> 47 public static void SetCookie(string cookiename, string cookievalue, DateTime expireTime) 48 { 49 var cookie = new HttpCookie(cookiename) 50 { 51 Value = cookievalue, 52 Expires = expireTime 53 }; 54 HttpContext.Current.Response.Cookies.Add(cookie); 55 } 56 }
CookieHelper
1 public class EMailHelper 2 { 3 /// <summary> 4 /// 邮件服务器地址 5 /// </summary> 6 public string EMailServer { get; set; } 7 /// <summary> 8 /// 用户名 9 /// </summary> 10 public string EMailUserName { get; set; } 11 /// <summary> 12 /// 密码 13 /// </summary> 14 public string EMailPassword { get; set; } 15 /// <summary> 16 /// 名称 17 /// </summary> 18 public string EMailName { get; set; } 19 20 /// <summary> 21 /// 同步发送邮件 22 /// </summary> 23 /// <param name="to">收件人邮箱地址</param> 24 /// <param name="subject">主题</param> 25 /// <param name="body">内容</param> 26 /// <param name="encoding">编码</param> 27 /// <param name="isBodyHtml">是否Html</param> 28 /// <param name="enableSsl">是否SSL加密连接</param> 29 /// <returns>是否成功</returns> 30 public bool Send(string to, string subject, string body, string encoding = "UTF-8", bool isBodyHtml = true, bool enableSsl = false) 31 { 32 try 33 { 34 MailMessage message = new MailMessage(); 35 // 接收人邮箱地址 36 message.To.Add(new MailAddress(to)); 37 message.From = new MailAddress(EMailUserName, EMailName); 38 message.BodyEncoding = Encoding.GetEncoding(encoding); 39 message.Body = body; 40 //GB2312 41 message.SubjectEncoding = Encoding.GetEncoding(encoding); 42 message.Subject = subject; 43 message.IsBodyHtml = isBodyHtml; 44 45 SmtpClient smtpclient = new SmtpClient(EMailServer, 25); 46 smtpclient.Credentials = new System.Net.NetworkCredential(EMailUserName, EMailPassword); 47 //SSL连接 48 smtpclient.EnableSsl = enableSsl; 49 smtpclient.Send(message); 50 return true; 51 } 52 catch (Exception) 53 { 54 throw; 55 } 56 } 57 /// <summary> 58 /// 异步发送邮件 独立线程 59 /// </summary> 60 /// <param name="to">邮件接收人</param> 61 /// <param name="title">邮件标题</param> 62 /// <param name="body">邮件内容</param> 63 /// <param name="port">端口号</param> 64 /// <returns></returns> 65 public void SendByThread(string to, string title, string body, int port = 25) 66 { 67 new Thread(new ThreadStart(delegate() 68 { 69 try 70 { 71 SmtpClient smtp = new SmtpClient(); 72 //邮箱的smtp地址 73 smtp.Host = EMailServer; 74 //端口号 75 smtp.Port = port; 76 //构建发件人的身份凭据类 77 smtp.Credentials = new NetworkCredential(EMailUserName, EMailPassword); 78 //构建消息类 79 MailMessage objMailMessage = new MailMessage(); 80 //设置优先级 81 objMailMessage.Priority = MailPriority.High; 82 //消息发送人 83 objMailMessage.From = new MailAddress(EMailUserName, EMailName, System.Text.Encoding.UTF8); 84 //收件人 85 objMailMessage.To.Add(to); 86 //标题 87 objMailMessage.Subject = title.Trim(); 88 //标题字符编码 89 objMailMessage.SubjectEncoding = System.Text.Encoding.UTF8; 90 //正文 91 objMailMessage.Body = body.Trim(); 92 objMailMessage.IsBodyHtml = true; 93 //内容字符编码 94 objMailMessage.BodyEncoding = System.Text.Encoding.UTF8; 95 //发送 96 smtp.Send(objMailMessage); 97 } 98 catch (Exception) 99 { 100 throw; 101 } 102 103 })).Start(); 104 } 105 }
EMailHelper
1 public class CryptoHelper 2 { 3 #region MD5加密 4 5 /// <summary> 6 /// MD5加密 7 /// </summary> 8 /// <param name="plainText">明文</param> 9 /// <returns></returns> 10 public static string MD5Encrypt(string plainText) 11 { 12 MD5 md5 = new MD5CryptoServiceProvider(); 13 byte[] fromData = Encoding.Unicode.GetBytes(plainText); 14 byte[] targetData = md5.ComputeHash(fromData); 15 string byte2String = null; 16 for (int i = 0; i < targetData.Length; i++) 17 { 18 byte2String += targetData[i].ToString("x"); 19 } 20 return byte2String; 21 22 //以下方法亦可 23 //string MD5encryptStr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile( 24 // plainText, "MD5"); 25 //return MD5encryptStr; 26 } 27 28 #endregion 29 30 #region DES加密 31 32 /// <summary> 33 /// DES加密 34 /// </summary> 35 /// <param name="plainText"></param> 36 /// <returns></returns> 37 public static string DESEncrypt(string plainText) 38 { 39 return DESEncrypt(plainText, "Mcmurphy"); 40 } 41 42 /// <summary> 43 /// DES加密 44 /// </summary> 45 /// <param name="plainText"></param> 46 /// <param name="sKey"></param> 47 /// <returns></returns> 48 public static string DESEncrypt(string plainText, string sKey) 49 { 50 var des = new DESCryptoServiceProvider(); 51 byte[] inputByteArray = Encoding.Default.GetBytes(plainText); 52 var hashPasswordForStoringInConfigFile = 53 System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5"); 54 if (hashPasswordForStoringInConfigFile != null) 55 des.Key = Encoding.ASCII.GetBytes(hashPasswordForStoringInConfigFile.Substring(0, 8)); 56 57 var passwordForStoringInConfigFile = 58 System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5"); 59 if (passwordForStoringInConfigFile != null) 60 des.IV = Encoding.ASCII.GetBytes(passwordForStoringInConfigFile.Substring(0, 8)); 61 62 var ms = new MemoryStream(); 63 var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); 64 cs.Write(inputByteArray, 0, inputByteArray.Length); 65 cs.FlushFinalBlock(); 66 var ret = new StringBuilder(); 67 foreach (byte b in ms.ToArray()) 68 { 69 ret.AppendFormat("{0:X2}", b); 70 } 71 return ret.ToString(); 72 } 73 74 #endregion 75 76 #region DES解密 77 78 79 /// <summary> 80 /// DES解密 81 /// </summary> 82 /// <param name="plainText"></param> 83 /// <returns></returns> 84 public static string DESDecrypt(string plainText) 85 { 86 return DESDecrypt(plainText, "Mcmurphy"); 87 } 88 89 /// <summary> 90 /// DES解密 91 /// </summary> 92 /// <param name="plainText"></param> 93 /// <param name="sKey"></param> 94 /// <returns></returns> 95 public static string DESDecrypt(string plainText, string sKey) 96 { 97 var des = new DESCryptoServiceProvider(); 98 int len = plainText.Length/2; 99 var inputByteArray = new byte[len]; 100 int x; 101 for (x = 0; x < len; x++) 102 { 103 int i = Convert.ToInt32(plainText.Substring(x*2, 2), 16); 104 inputByteArray[x] = (byte) i; 105 } 106 var hashPasswordForStoringInConfigFile = 107 System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5"); 108 if (hashPasswordForStoringInConfigFile != null) 109 des.Key = Encoding.ASCII.GetBytes(hashPasswordForStoringInConfigFile.Substring(0, 8)); 110 111 var passwordForStoringInConfigFile = 112 System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5"); 113 if (passwordForStoringInConfigFile != null) 114 des.IV = Encoding.ASCII.GetBytes(passwordForStoringInConfigFile.Substring(0, 8)); 115 116 var ms = new MemoryStream(); 117 var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); 118 cs.Write(inputByteArray, 0, inputByteArray.Length); 119 cs.FlushFinalBlock(); 120 return Encoding.Default.GetString(ms.ToArray()); 121 } 122 123 #endregion 124 125 #region TripleDES加密 126 127 /// <summary> 128 /// TripleDES加密 129 /// </summary> 130 public static string TripleDESEncrypting(string strSource) 131 { 132 try 133 { 134 byte[] bytIn = Encoding.Default.GetBytes(strSource); 135 byte[] key = { 136 42, 16, 93, 156, 78, 4, 218, 32, 15, 167, 44, 80, 26, 20, 155, 112, 2, 94, 11, 204, 119 137 , 138 35, 184, 197 139 }; //定义密钥 140 byte[] IV = {55, 103, 246, 79, 36, 99, 167, 3}; //定义偏移量 141 var TripleDES = new TripleDESCryptoServiceProvider {IV = IV, Key = key}; 142 ICryptoTransform encrypto = TripleDES.CreateEncryptor(); 143 var ms = new MemoryStream(); 144 var cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write); 145 cs.Write(bytIn, 0, bytIn.Length); 146 cs.FlushFinalBlock(); 147 byte[] bytOut = ms.ToArray(); 148 return Convert.ToBase64String(bytOut); 149 } 150 catch (Exception ex) 151 { 152 throw new Exception("加密时候出现错误!错误提示:\n" + ex.Message); 153 } 154 } 155 156 #endregion 157 158 #region TripleDES解密 159 160 /// <summary> 161 /// TripleDES解密 162 /// </summary> 163 public static string TripleDESDecrypting(string Source) 164 { 165 try 166 { 167 byte[] bytIn = Convert.FromBase64String(Source); 168 byte[] key = { 169 42, 16, 93, 156, 78, 4, 218, 32, 15, 167, 44, 80, 26, 20, 155, 112, 2, 94, 11, 204, 119 170 , 171 35, 184, 197 172 }; //定义密钥 173 byte[] IV = {55, 103, 246, 79, 36, 99, 167, 3}; //定义偏移量 174 var TripleDES = new TripleDESCryptoServiceProvider {IV = IV, Key = key}; 175 ICryptoTransform encrypto = TripleDES.CreateDecryptor(); 176 var ms = new MemoryStream(bytIn, 0, bytIn.Length); 177 var cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read); 178 var strd = new StreamReader(cs, Encoding.Default); 179 return strd.ReadToEnd(); 180 } 181 catch (Exception ex) 182 { 183 throw new Exception("解密时候出现错误!错误提示:\n" + ex.Message); 184 } 185 } 186 187 #endregion 188 189 }
加密Dog
1 /// <summary> 2 /// 文件操作夹(暂时未支持跨平台) 3 /// </summary> 4 public static class DirFileHelper 5 { 6 #region 检测指定目录是否存在 7 /// <summary> 8 /// 检测指定目录是否存在 9 /// </summary> 10 /// <param name="directoryPath">目录的绝对路径</param> 11 /// <returns></returns> 12 public static bool IsExistDirectory(string directoryPath) 13 { 14 return Directory.Exists(directoryPath); 15 } 16 #endregion 17 18 #region 检测指定文件是否存在,如果存在返回true 19 /// <summary> 20 /// 检测指定文件是否存在,如果存在则返回true。 21 /// </summary> 22 /// <param name="filePath">文件的绝对路径</param> 23 public static bool IsExistFile(string filePath) 24 { 25 return File.Exists(filePath); 26 } 27 #endregion 28 29 #region 获取指定目录中的文件列表 30 /// <summary> 31 /// 获取指定目录中所有文件列表 32 /// </summary> 33 /// <param name="directoryPath">指定目录的绝对路径</param> 34 public static string[] GetFileNames(string directoryPath) 35 { 36 //如果目录不存在,则抛出异常 37 if (!IsExistDirectory(directoryPath)) 38 { 39 throw new FileNotFoundException(); 40 } 41 42 //获取文件列表 43 return Directory.GetFiles(directoryPath); 44 } 45 #endregion 46 47 #region 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法. 48 /// <summary> 49 /// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法. 50 /// </summary> 51 /// <param name="directoryPath">指定目录的绝对路径</param> 52 public static string[] GetDirectories(string directoryPath) 53 { 54 try 55 { 56 return Directory.GetDirectories(directoryPath); 57 } 58 catch (IOException ex) 59 { 60 throw ex; 61 } 62 } 63 #endregion 64 65 #region 获取指定目录及子目录中所有文件列表 66 /// <summary> 67 /// 获取指定目录及子目录中所有文件列表 68 /// </summary> 69 /// <param name="directoryPath">指定目录的绝对路径</param> 70 /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。 71 /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param> 72 /// <param name="isSearchChild">是否搜索子目录</param> 73 public static string[] GetFileNames(string directoryPath, string searchPattern, bool isSearchChild) 74 { 75 //如果目录不存在,则抛出异常 76 if (!IsExistDirectory(directoryPath)) 77 { 78 throw new FileNotFoundException(); 79 } 80 81 try 82 { 83 if (isSearchChild) 84 { 85 return Directory.GetFiles(directoryPath, searchPattern, SearchOption.AllDirectories); 86 } 87 else 88 { 89 return Directory.GetFiles(directoryPath, searchPattern, SearchOption.TopDirectoryOnly); 90 } 91 } 92 catch (IOException ex) 93 { 94 throw ex; 95 } 96 } 97 #endregion 98 99 #region 检测指定目录是否为空 100 /// <summary> 101 /// 检测指定目录是否为空 102 /// </summary> 103 /// <param name="directoryPath">指定目录的绝对路径</param> 104 public static bool IsEmptyDirectory(string directoryPath) 105 { 106 try 107 { 108 //判断是否存在文件 109 string[] fileNames = GetFileNames(directoryPath); 110 if (fileNames.Length > 0) 111 { 112 return false; 113 } 114 115 //判断是否存在文件夹 116 string[] directoryNames = GetDirectories(directoryPath); 117 if (directoryNames.Length > 0) 118 { 119 return false; 120 } 121 122 return true; 123 } 124 catch 125 { 126 //这里记录日志 127 //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message); 128 return true; 129 } 130 } 131 #endregion 132 133 #region 检测指定目录中是否存在指定的文件 134 /// <summary> 135 /// 检测指定目录中是否存在指定的文件,若要搜索子目录请使用重载方法. 136 /// </summary> 137 /// <param name="directoryPath">指定目录的绝对路径</param> 138 /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。 139 /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param> 140 public static bool Contains(string directoryPath, string searchPattern) 141 { 142 try 143 { 144 //获取指定的文件列表 145 string[] fileNames = GetFileNames(directoryPath, searchPattern, false); 146 147 //判断指定文件是否存在 148 if (fileNames.Length == 0) 149 { 150 return false; 151 } 152 else 153 { 154 return true; 155 } 156 } 157 catch (Exception ex) 158 { 159 throw new Exception(ex.Message); 160 //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message); 161 } 162 } 163 164 /// <summary> 165 /// 检测指定目录中是否存在指定的文件 166 /// </summary> 167 /// <param name="directoryPath">指定目录的绝对路径</param> 168 /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。 169 /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param> 170 /// <param name="isSearchChild">是否搜索子目录</param> 171 public static bool Contains(string directoryPath, string searchPattern, bool isSearchChild) 172 { 173 try 174 { 175 //获取指定的文件列表 176 string[] fileNames = GetFileNames(directoryPath, searchPattern, true); 177 178 //判断指定文件是否存在 179 if (fileNames.Length == 0) 180 { 181 return false; 182 } 183 else 184 { 185 return true; 186 } 187 } 188 catch (Exception ex) 189 { 190 throw new Exception(ex.Message); 191 //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message); 192 } 193 } 194 #endregion 195 196 #region 创建目录 197 /// <summary> 198 /// 创建目录 199 /// </summary> 200 /// <param name="dir">要创建的目录路径包括目录名</param> 201 public static void CreateDir(string dir) 202 { 203 if (dir.Length == 0) return; 204 if (!Directory.Exists(dir)) 205 Directory.CreateDirectory(dir); 206 } 207 #endregion 208 209 #region 删除目录 210 /// <summary> 211 /// 删除目录 212 /// </summary> 213 /// <param name="dir">要删除的目录路径和名称</param> 214 public static void DeleteDir(string dir) 215 { 216 if (dir.Length == 0) return; 217 if (Directory.Exists(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir)) 218 Directory.Delete(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir); 219 } 220 #endregion 221 222 #region 删除文件 223 /// <summary> 224 /// 删除文件 225 /// </summary> 226 /// <param name="file">要删除的文件路径和名称</param> 227 public static void DeleteFile(string file) 228 { 229 if (File.Exists( file)) 230 File.Delete( file); 231 } 232 #endregion 233 234 #region 创建文件 235 /// <summary> 236 /// 创建文件 237 /// </summary> 238 /// <param name="dir">带后缀的文件名</param> 239 /// <param name="pagestr">文件内容</param> 240 public static void CreateFile(string dir, string pagestr) 241 { 242 dir = dir.Replace("/", "\\"); 243 if (dir.IndexOf("\\") > -1) 244 CreateDir(dir.Substring(0, dir.LastIndexOf("\\"))); 245 System.IO.StreamWriter sw = new System.IO.StreamWriter(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir, false, System.Text.Encoding.GetEncoding("GB2312")); 246 sw.Write(pagestr); 247 sw.Close(); 248 } 249 #endregion 250 251 #region 移动文件(剪贴--粘贴) 252 /// <summary> 253 /// 移动文件(剪贴--粘贴) 254 /// </summary> 255 /// <param name="dir1">要移动的文件的路径及全名(包括后缀)</param> 256 /// <param name="dir2">文件移动到新的位置,并指定新的文件名</param> 257 public static void MoveFile(string dir1, string dir2) 258 { 259 dir1 = dir1.Replace("/", "\\"); 260 dir2 = dir2.Replace("/", "\\"); 261 if (File.Exists(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir1)) 262 File.Move(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir1, System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir2); 263 } 264 #endregion 265 266 #region 复制文件 267 /// <summary> 268 /// 复制文件 269 /// </summary> 270 /// <param name="dir1">要复制的文件的路径已经全名(包括后缀)</param> 271 /// <param name="dir2">目标位置,并指定新的文件名</param> 272 public static void CopyFile(string dir1, string dir2) 273 { 274 //dir1 = dir1.Replace("/", "\\"); 275 //dir2 = dir2.Replace("/", "\\"); 276 if (File.Exists(dir1)) 277 { 278 File.Copy(dir1,dir2, true); 279 } 280 /*if (File.Exists(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir1)) 281 { 282 File.Copy(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir1, System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + dir2, true); 283 }*/ 284 } 285 #endregion 286 287 #region 根据时间得到目录名 / 格式:yyyyMMdd 或者 HHmmssff 288 /// <summary> 289 /// 根据时间得到目录名yyyyMMdd 290 /// </summary> 291 /// <returns></returns> 292 public static string GetDateDir() 293 { 294 return DateTime.Now.ToString("yyyyMMdd"); 295 } 296 /// <summary> 297 /// 根据时间得到文件名HHmmssff 298 /// </summary> 299 /// <returns></returns> 300 public static string GetDateFile() 301 { 302 return DateTime.Now.ToString("HHmmssff"); 303 } 304 #endregion 305 306 #region 复制文件夹 307 /// <summary> 308 /// 复制文件夹(递归) 309 /// </summary> 310 /// <param name="varFromDirectory">源文件夹路径</param> 311 /// <param name="varToDirectory">目标文件夹路径</param> 312 public static void CopyFolder(string varFromDirectory, string varToDirectory) 313 { 314 Directory.CreateDirectory(varToDirectory); 315 316 if (!Directory.Exists(varFromDirectory)) return; 317 318 string[] directories = Directory.GetDirectories(varFromDirectory); 319 320 if (directories.Length > 0) 321 { 322 foreach (string d in directories) 323 { 324 CopyFolder(d, varToDirectory + d.Substring(d.LastIndexOf("\\"))); 325 } 326 } 327 string[] files = Directory.GetFiles(varFromDirectory); 328 if (files.Length > 0) 329 { 330 foreach (string s in files) 331 { 332 File.Copy(s, varToDirectory + s.Substring(s.LastIndexOf("\\")), true); 333 } 334 } 335 } 336 #endregion 337 338 #region 检查文件,如果文件不存在则创建 339 /// <summary> 340 /// 检查文件,如果文件不存在则创建 341 /// </summary> 342 /// <param name="FilePath">路径,包括文件名</param> 343 public static void ExistsFile(string FilePath) 344 { 345 //if(!File.Exists(FilePath)) 346 //File.Create(FilePath); 347 //以上写法会报错,详细解释请看下文......... 348 if (!File.Exists(FilePath)) 349 { 350 FileStream fs = File.Create(FilePath); 351 fs.Close(); 352 } 353 } 354 #endregion 355 356 #region 删除指定文件夹对应其他文件夹里的文件 357 /// <summary> 358 /// 删除指定文件夹对应其他文件夹里的文件 359 /// </summary> 360 /// <param name="varFromDirectory">指定文件夹路径</param> 361 /// <param name="varToDirectory">对应其他文件夹路径</param> 362 public static void DeleteFolderFiles(string varFromDirectory, string varToDirectory) 363 { 364 Directory.CreateDirectory(varToDirectory); 365 366 if (!Directory.Exists(varFromDirectory)) return; 367 368 string[] directories = Directory.GetDirectories(varFromDirectory); 369 370 if (directories.Length > 0) 371 { 372 foreach (string d in directories) 373 { 374 DeleteFolderFiles(d, varToDirectory + d.Substring(d.LastIndexOf("\\"))); 375 } 376 } 377 378 379 string[] files = Directory.GetFiles(varFromDirectory); 380 381 if (files.Length > 0) 382 { 383 foreach (string s in files) 384 { 385 File.Delete(varToDirectory + s.Substring(s.LastIndexOf("\\"))); 386 } 387 } 388 } 389 #endregion 390 391 #region 从文件的绝对路径中获取文件名( 包含扩展名 ) 392 /// <summary> 393 /// 从文件的绝对路径中获取文件名( 包含扩展名 ) 394 /// </summary> 395 /// <param name="filePath">文件的绝对路径</param> 396 public static string GetFileName(string filePath) 397 { 398 //获取文件的名称 399 FileInfo fi = new FileInfo(filePath); 400 return fi.Name; 401 } 402 #endregion 403 404 #region 创建一个目录 405 /// <summary> 406 /// 创建一个目录 407 /// </summary> 408 /// <param name="directoryPath">目录的绝对路径</param> 409 public static bool CreateDirectory(string directoryPath) 410 { 411 //如果目录不存在则创建该目录 412 if (!IsExistDirectory(directoryPath)) 413 { 414 try 415 { 416 Directory.CreateDirectory(directoryPath); 417 return true; 418 } 419 catch{ 420 return false; 421 } 422 } 423 else { 424 return false; 425 } 426 } 427 #endregion 428 429 #region 创建一个文件 430 /// <summary> 431 /// 创建一个文件。 432 /// </summary> 433 /// <param name="filePath">文件的绝对路径</param> 434 public static void CreateFile(string filePath) 435 { 436 try 437 { 438 //如果文件不存在则创建该文件 439 if (!IsExistFile(filePath)) 440 { 441 //创建一个FileInfo对象 442 FileInfo file = new FileInfo(filePath); 443 444 //创建文件 445 FileStream fs = file.Create(); 446 447 //关闭文件流 448 fs.Close(); 449 } 450 } 451 catch (Exception ex) 452 { 453 //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message); 454 throw ex; 455 } 456 } 457 458 /// <summary> 459 /// 创建一个文件,并将字节流写入文件。 460 /// </summary> 461 /// <param name="filePath">文件的绝对路径</param> 462 /// <param name="buffer">二进制流数据</param> 463 public static void CreateFile(string filePath, byte[] buffer) 464 { 465 try 466 { 467 //如果文件不存在则创建该文件 468 if (!IsExistFile(filePath)) 469 { 470 //创建一个FileInfo对象 471 FileInfo file = new FileInfo(filePath); 472 473 //创建文件 474 FileStream fs = file.Create(); 475 476 //写入二进制流 477 fs.Write(buffer, 0, buffer.Length); 478 479 //关闭文件流 480 fs.Close(); 481 } 482 } 483 catch (Exception ex) 484 { 485 //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message); 486 throw ex; 487 } 488 } 489 #endregion 490 491 #region 获取文本文件的行数 492 /// <summary> 493 /// 获取文本文件的行数 494 /// </summary> 495 /// <param name="filePath">文件的绝对路径</param> 496 public static int GetLineCount(string filePath) 497 { 498 //将文本文件的各行读到一个字符串数组中 499 string[] rows = File.ReadAllLines(filePath); 500 501 //返回行数 502 return rows.Length; 503 } 504 #endregion 505 506 #region 获取一个文件的长度 507 /// <summary> 508 /// 获取一个文件的长度,单位为Byte 509 /// </summary> 510 /// <param name="filePath">文件的绝对路径</param> 511 public static int GetFileSize(string filePath) 512 { 513 //创建一个文件对象 514 FileInfo fi = new FileInfo(filePath); 515 516 //获取文件的大小 517 return (int)fi.Length; 518 } 519 #endregion 520 521 #region 获取指定目录中的子目录列表 522 /// <summary> 523 /// 获取指定目录及子目录中所有子目录列表 524 /// </summary> 525 /// <param name="directoryPath">指定目录的绝对路径</param> 526 /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。 527 /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param> 528 /// <param name="isSearchChild">是否搜索子目录</param> 529 public static string[] GetDirectories(string directoryPath, string searchPattern, bool isSearchChild) 530 { 531 try 532 { 533 if (isSearchChild) 534 { 535 return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.AllDirectories); 536 } 537 else 538 { 539 return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.TopDirectoryOnly); 540 } 541 } 542 catch (IOException ex) 543 { 544 throw ex; 545 } 546 } 547 #endregion 548 549 #region 向文本文件写入内容 550 551 /// <summary> 552 /// 向文本文件中写入内容 553 /// </summary> 554 /// <param name="filePath">文件的绝对路径</param> 555 /// <param name="text">写入的内容</param> 556 /// <param name="encoding">编码</param> 557 public static void WriteText(string filePath, string text, Encoding encoding) 558 { 559 //向文件写入内容 560 File.WriteAllText(filePath, text, encoding); 561 } 562 #endregion 563 564 #region 向文本文件的尾部追加内容 565 /// <summary> 566 /// 向文本文件的尾部追加内容 567 /// </summary> 568 /// <param name="filePath">文件的绝对路径</param> 569 /// <param name="content">写入的内容</param> 570 public static void AppendText(string filePath, string content) 571 { 572 File.AppendAllText(filePath, content); 573 } 574 #endregion 575 576 #region 将现有文件的内容复制到新文件中 577 /// <summary> 578 /// 将源文件的内容复制到目标文件中 579 /// </summary> 580 /// <param name="sourceFilePath">源文件的绝对路径</param> 581 /// <param name="destFilePath">目标文件的绝对路径</param> 582 public static void Copy(string sourceFilePath, string destFilePath) 583 { 584 File.Copy(sourceFilePath, destFilePath, true); 585 } 586 #endregion 587 588 #region 将文件移动到指定目录 589 /// <summary> 590 /// 将文件移动到指定目录 591 /// </summary> 592 /// <param name="sourceFilePath">需要移动的源文件的绝对路径</param> 593 /// <param name="descDirectoryPath">移动到的目录的绝对路径</param> 594 public static void Move(string sourceFilePath, string descDirectoryPath) 595 { 596 //获取源文件的名称 597 string sourceFileName = GetFileName(sourceFilePath); 598 599 if (IsExistDirectory(descDirectoryPath)) 600 { 601 //如果目标中存在同名文件,则删除 602 if (IsExistFile(descDirectoryPath + "\\" + sourceFileName)) 603 { 604 DeleteFile(descDirectoryPath + "\\" + sourceFileName); 605 } 606 //将文件移动到指定目录 607 File.Move(sourceFilePath, descDirectoryPath + "\\" + sourceFileName); 608 } 609 } 610 #endregion 611 612 #region 从文件的绝对路径中获取文件名( 不包含扩展名 ) 613 /// <summary> 614 /// 从文件的绝对路径中获取文件名( 不包含扩展名 ) 615 /// </summary> 616 /// <param name="filePath">文件的绝对路径</param> 617 public static string GetFileNameNoExtension(string filePath) 618 { 619 //获取文件的名称 620 FileInfo fi = new FileInfo(filePath); 621 return fi.Name.Split(‘.‘)[0]; 622 } 623 #endregion 624 625 #region 从文件的绝对路径中获取扩展名 626 /// <summary> 627 /// 从文件的绝对路径中获取扩展名 628 /// </summary> 629 /// <param name="filePath">文件的绝对路径</param> 630 public static string GetExtension(string filePath) 631 { 632 //获取文件的名称 633 FileInfo fi = new FileInfo(filePath); 634 return fi.Extension; 635 } 636 #endregion 637 638 #region 清空指定目录 639 /// <summary> 640 /// 清空指定目录下所有文件及子目录,但该目录依然保存. 641 /// </summary> 642 /// <param name="directoryPath">指定目录的绝对路径</param> 643 public static void ClearDirectory(string directoryPath) 644 { 645 if (IsExistDirectory(directoryPath)) 646 { 647 //删除目录中所有的文件 648 string[] fileNames = GetFileNames(directoryPath); 649 for (int i = 0; i < fileNames.Length; i++) 650 { 651 DeleteFile(fileNames[i]); 652 } 653 654 //删除目录中所有的子目录 655 string[] directoryNames = GetDirectories(directoryPath); 656 for (int i = 0; i < directoryNames.Length; i++) 657 { 658 DeleteDirectory(directoryNames[i]); 659 } 660 } 661 } 662 #endregion 663 664 #region 清空文件内容 665 /// <summary> 666 /// 清空文件内容 667 /// </summary> 668 /// <param name="filePath">文件的绝对路径</param> 669 public static void ClearFile(string filePath) 670 { 671 //删除文件 672 File.Delete(filePath); 673 674 //重新创建该文件 675 CreateFile(filePath); 676 } 677 #endregion 678 679 #region 删除指定目录 680 /// <summary> 681 /// 删除指定目录及其所有子目录 682 /// </summary> 683 /// <param name="directoryPath">指定目录的绝对路径</param> 684 public static void DeleteDirectory(string directoryPath) 685 { 686 if (IsExistDirectory(directoryPath)) 687 { 688 Directory.Delete(directoryPath, true); 689 } 690 } 691 #endregion 692 }
DirFileHelper
1 /// <summary> 2 /// 文件下载类 3 /// </summary> 4 public class FileDownHelper 5 { 6 public FileDownHelper() 7 { } 8 /// <summary> 9 /// 获取文件扩展名 10 /// </summary> 11 public static string FileNameExtension(string FileName) 12 { 13 return Path.GetExtension(MapPathFile(FileName)); 14 } 15 16 /// <summary> 17 /// 获取物理地址 18 /// </summary> 19 public static string MapPathFile(string FileName) 20 { 21 return HttpContext.Current.Server.MapPath(FileName); 22 } 23 /// <summary> 24 /// 验证文件是否存在 25 /// </summary> 26 /// <param name="FileName"></param> 27 /// <returns></returns> 28 public static bool FileExists(string FileName) 29 { 30 string destFileName = FileName; 31 if (File.Exists(destFileName)) 32 { 33 return true; 34 } 35 else 36 { 37 return false; 38 } 39 } 40 /// <summary> 41 /// 普通下载 42 /// </summary> 43 /// <param name="fileName">文件虚拟路径</param> 44 /// /// <param name="name">返回给客户端的文件名称</param> 45 public static void DownLoadold(string fileName, string name) 46 { 47 string destFileName = fileName; 48 if (File.Exists(destFileName)) 49 { 50 FileInfo fi = new FileInfo(destFileName); 51 HttpContext.Current.Response.Clear(); 52 HttpContext.Current.Response.ClearHeaders(); 53 HttpContext.Current.Response.Buffer = false; 54 HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8)); 55 HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString()); 56 HttpContext.Current.Response.ContentType = "application/octet-stream"; 57 HttpContext.Current.Response.WriteFile(destFileName); 58 HttpContext.Current.Response.Flush(); 59 HttpContext.Current.Response.End(); 60 } 61 } 62 63 /// <summary> 64 /// 分块下载 65 /// </summary> 66 /// <param name="FileName">文件虚拟路径</param> 67 public static void DownLoad(string FileName) 68 { 69 string filePath = MapPathFile(FileName); 70 long chunkSize = 204800; //指定块大小 71 byte[] buffer = new byte[chunkSize]; //建立一个200K的缓冲区 72 long dataToRead = 0; //已读的字节数 73 FileStream stream = null; 74 try 75 { 76 //打开文件 77 stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); 78 dataToRead = stream.Length; 79 80 //添加Http头 81 HttpContext.Current.Response.ContentType = "application/octet-stream"; 82 HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + HttpUtility.UrlEncode(Path.GetFileName(filePath))); 83 HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString()); 84 85 while (dataToRead > 0) 86 { 87 if (HttpContext.Current.Response.IsClientConnected) 88 { 89 int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize)); 90 HttpContext.Current.Response.OutputStream.Write(buffer, 0, length); 91 HttpContext.Current.Response.Flush(); 92 HttpContext.Current.Response.Clear(); 93 dataToRead -= length; 94 } 95 else 96 { 97 dataToRead = -1; //防止client失去连接 98 } 99 } 100 } 101 catch (Exception ex) 102 { 103 HttpContext.Current.Response.Write("Error:" + ex.Message); 104 } 105 finally 106 { 107 if (stream != null) stream.Close(); 108 HttpContext.Current.Response.Close(); 109 } 110 } 111 112 /// <summary> 113 /// 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小 114 /// </summary> 115 /// <param name="_Request">Page.Request对象</param> 116 /// <param name="_Response">Page.Response对象</param> 117 /// <param name="_fileName">下载文件名</param> 118 /// <param name="_fullPath">带文件名下载路径</param> 119 /// <param name="_speed">每秒允许下载的字节数</param> 120 /// <returns>返回是否成功</returns> 121 //--------------------------------------------------------------------- 122 //调用: 123 // string FullPath=Server.MapPath("count.txt"); 124 // ResponseFile(this.Request,this.Response,"count.txt",FullPath,100); 125 //--------------------------------------------------------------------- 126 public static bool ResponseFile(ControllerContext context, string _fileName, string _fullPath, long _speed) 127 { 128 HttpRequestBase _Request = context.HttpContext.Request; 129 HttpResponseBase _Response = context.HttpContext.Response; 130 try 131 { 132 133 FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); 134 BinaryReader br = new BinaryReader(myFile); 135 try 136 { 137 _Response.AddHeader("Accept-Ranges", "bytes"); 138 _Response.Buffer = false; 139 140 long fileLength = myFile.Length; 141 long startBytes = 0; 142 int pack = 10240; //10K bytes 143 int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1; 144 145 if (_Request.Headers["Range"] != null) 146 { 147 _Response.StatusCode = 206; 148 string[] range = _Request.Headers["Range"].Split(new char[] { ‘=‘, ‘-‘ }); 149 startBytes = Convert.ToInt64(range[1]); 150 } 151 _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString()); 152 if (startBytes != 0) 153 { 154 _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength)); 155 } 156 157 _Response.AddHeader("Connection", "Keep-Alive"); 158 _Response.ContentType = "application/octet-stream"; 159 _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8)); 160 161 br.BaseStream.Seek(startBytes, SeekOrigin.Begin); 162 int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1; 163 164 for (int i = 0; i < maxCount; i++) 165 { 166 if (_Response.IsClientConnected) 167 { 168 _Response.BinaryWrite(br.ReadBytes(pack)); 169 Thread.Sleep(sleep); 170 } 171 else 172 { 173 i = maxCount; 174 } 175 } 176 } 177 catch 178 { 179 return false; 180 } 181 finally 182 { 183 br.Close(); 184 myFile.Close(); 185 } 186 } 187 catch 188 { 189 return false; 190 } 191 return true; 192 } 193 194 195 public static bool ResponseFile1(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed) 196 { 197 try 198 { 199 200 FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); 201 BinaryReader br = new BinaryReader(myFile); 202 try 203 { 204 _Response.AddHeader("Accept-Ranges", "bytes"); 205 _Response.Buffer = false; 206 207 long fileLength = myFile.Length; 208 long startBytes = 0; 209 int pack = 10240; //10K bytes 210 int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1; 211 212 if (_Request.Headers["Range"] != null) 213 { 214 _Response.StatusCode = 206; 215 string[] range = _Request.Headers["Range"].Split(new char[] { ‘=‘, ‘-‘ }); 216 startBytes = Convert.ToInt64(range[1]); 217 } 218 _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString()); 219 if (startBytes != 0) 220 { 221 _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength)); 222 } 223 224 _Response.AddHeader("Connection", "Keep-Alive"); 225 _Response.ContentType = "application/octet-stream"; 226 _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8)); 227 228 br.BaseStream.Seek(startBytes, SeekOrigin.Begin); 229 int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1; 230 231 for (int i = 0; i < maxCount; i++) 232 { 233 if (_Response.IsClientConnected) 234 { 235 _Response.BinaryWrite(br.ReadBytes(pack)); 236 Thread.Sleep(sleep); 237 } 238 else 239 { 240 i = maxCount; 241 } 242 } 243 } 244 catch 245 { 246 return false; 247 } 248 finally 249 { 250 br.Close(); 251 myFile.Close(); 252 } 253 } 254 catch 255 { 256 return false; 257 } 258 return true; 259 } 260 }
FileDownHelper
1 public class ImageHelper 2 { 3 /// <summary> 4 /// 生成缩略图 5 /// </summary> 6 /// <param name="orignPath">源图路径(绝对路径)</param> 7 /// <param name="thumbPath">缩略图路径(绝对路径)</param> 8 /// <param name="width">缩略图宽度</param> 9 /// <param name="height">缩略图高度</param> 10 /// <param name="mode">生成缩略图的方式</param> 11 public static void MakeThumbnailImage(string orignPath, string thumbPath, int width, int height, string mode) 12 { 13 var originalImage = Image.FromFile(orignPath); 14 int towidth = width; 15 int toheight = height; 16 17 int x = 0; 18 int y = 0; 19 int ow = originalImage.Width; 20 int oh = originalImage.Height; 21 switch (mode) 22 { 23 case "HW"://指定高宽缩放(可能变形) 24 break; 25 case "W"://指定宽,高按比例 26 toheight = originalImage.Height * width / originalImage.Width; 27 break; 28 case "H"://指定高,宽按比例 29 towidth = originalImage.Width * height / originalImage.Height; 30 break; 31 case "Cut"://指定高宽裁减(不变形) 32 if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) 33 { 34 oh = originalImage.Height; 35 ow = originalImage.Height * towidth / toheight; 36 y = 0; 37 x = (originalImage.Width - ow) / 2; 38 } 39 else 40 { 41 ow = originalImage.Width; 42 oh = originalImage.Width * height / towidth; 43 x = 0; 44 y = (originalImage.Height - oh) / 2; 45 } 46 break; 47 } 48 49 //新建一个bmp图片 50 var b = new Bitmap(towidth, toheight); 51 try 52 { 53 //新建一个画板 54 var g = Graphics.FromImage(b); 55 //设置高质量插值法 56 g.InterpolationMode = InterpolationMode.HighQualityBicubic; 57 //设置高质量,低速度呈现平滑程度 58 g.SmoothingMode = SmoothingMode.AntiAlias; 59 g.PixelOffsetMode = PixelOffsetMode.HighQuality; 60 //清空画布并以透明背景色填充 61 g.Clear(Color.Transparent); 62 //在指定位置并且按指定大小绘制原图片的指定部分 63 g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel); 64 //保存图像 65 b.Save(thumbPath); 66 } 67 finally 68 { 69 originalImage.Dispose(); 70 b.Dispose(); 71 } 72 } 73 }
ImageHelper
1 /// <summary> 2 /// 常用IO操作类 3 /// </summary> 4 public class IOHelper 5 { 6 /// <summary> 7 /// 系统路径转换为web路径地址 8 /// </summary> 9 /// <param name="fullPath">文件完整地址</param> 10 /// <param name="AppPath">应用地址</param> 11 /// <param name="dHear">是否去掉首部的分隔符</param> 12 /// <returns></returns> 13 public static string WebPathParse(string fullPath,string appPath,bool dHear) 14 { 15 string sys = Path.DirectorySeparatorChar.ToString(); 16 string web = @"/";//web的分隔符 17 if (fullPath.StartsWith(appPath)) 18 { 19 string webPath = fullPath.Remove(0, appPath.Length); 20 webPath = webPath.Replace(sys, web); 21 if (webPath.StartsWith(web) == false) 22 { 23 webPath = web + webPath; 24 } 25 if (dHear) 26 { 27 webPath = IOHelper.RemoveHead(webPath, web); 28 } 29 return webPath; 30 } 31 else { 32 return ""; 33 } 34 } 35 /// <summary> 36 /// web路径地址转换为系统路径 37 /// </summary> 38 /// <param name="appPath">应用路径</param> 39 /// <param name="webPath">web路径</param> 40 /// <param name="dHear">是否去掉首部的路径分隔符</param> 41 /// <returns></returns> 42 public static string SysPathParse(string appPath, string webPath, bool dHear) 43 { 44 string sys = Path.DirectorySeparatorChar.ToString(); 45 string web = @"/";//web的分隔符 46 webPath = webPath.Replace(web, sys); 47 if (dHear) 48 { 49 webPath = IOHelper.RemoveHead(webPath, sys); 50 } 51 string result=""; 52 if (appPath.EndsWith(sys)) 53 { 54 if (webPath.StartsWith(sys)) 55 { 56 result = appPath + webPath.Remove(0,1); 57 } 58 else 59 { 60 result = appPath + webPath; 61 } 62 } 63 else { 64 if (webPath.StartsWith(sys)) 65 { 66 result = appPath + webPath; 67 } 68 else { 69 result = appPath + sys + webPath; 70 } 71 } 72 return result; 73 } 74 /// <summary> 75 /// 路径解析转换,转化成符合当前系统的路径符号 76 /// </summary> 77 /// <param name="path">路径</param> 78 /// <param name="flag">(路径的类型)1:windows \ 2:linux /(linux和web网页的分隔相符)</param> 79 /// <param name="dHear">是否去掉首部的路径分隔符</param> 80 /// <returns></returns> 81 public static string PathParse(string path, int flag, bool dHear) 82 { 83 string win = @"\"; 84 string linux = @"/"; 85 string sys=Path.DirectorySeparatorChar.ToString(); 86 if (flag == 1) 87 { 88 path = path.Replace(win, sys); 89 } 90 else if (flag == 2) 91 { 92 path = path.Replace(linux, sys); 93 } 94 if (dHear) { 95 path = IOHelper.RemoveHead(path, sys); 96 } 97 return path; 98 } 99 /// <summary> 100 /// (递归)去掉所有首部出现的字符串 101 /// </summary> 102 /// <param name="str">源字符串</param> 103 /// <param name="headStr">首部出现的字符串</param> 104 /// <returns></returns> 105 public static string RemoveHead(string str, string headStr) 106 { 107 if (str.StartsWith(headStr)) 108 { 109 str = str.Remove(0, headStr.Length); 110 return RemoveHead(str, headStr); 111 } 112 else { 113 return str; 114 } 115 } 116 117 /// <summary> 118 /// 返回指定目录下目录信息 119 /// </summary> 120 /// <param name="strDirectory">路径</param> 121 /// <returns></returns> 122 public static DirectoryInfo[] GetDirectory(string strDirectory) 123 { 124 if (string.IsNullOrEmpty(strDirectory) == false) 125 { 126 return new DirectoryInfo(strDirectory).GetDirectories(); 127 } 128 return new DirectoryInfo[] { }; 129 } 130 /// <summary> 131 /// 返回指定目录下所有文件信息 132 /// </summary> 133 /// <param name="strDirectory">路径</param> 134 /// <returns></returns> 135 public static FileInfo[] GetFiles(string strDirectory) 136 { 137 if (string.IsNullOrEmpty(strDirectory) == false) 138 { 139 return new DirectoryInfo(strDirectory).GetFiles(); 140 } 141 return new FileInfo[] { }; 142 } 143 /// <summary> 144 /// 返回指定目录下过滤文件信息 145 /// </summary> 146 /// <param name="strDirectory">目录地址</param> 147 /// <param name="filter"></param> 148 /// <returns></returns> 149 public static FileInfo[] GetFiles(string strDirectory, string filter) 150 { 151 if (string.IsNullOrEmpty(strDirectory) == false) 152 { 153 return new DirectoryInfo(strDirectory).GetFiles(filter, SearchOption.TopDirectoryOnly); 154 } 155 return new FileInfo[] { }; 156 } 157 public static void WriteDebug(Exception ex) 158 { 159 Debug.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); 160 Debug.WriteLine("Data:" + ex.Data + Environment.NewLine 161 + " InnerException:" + ex.InnerException + Environment.NewLine 162 + " Message:" + ex.Message + Environment.NewLine 163 + " Source:" + ex.Source + Environment.NewLine 164 + " StackTrace:" + ex.StackTrace + Environment.NewLine 165 + " TargetSite:" + ex.TargetSite); 166 } 167 /// <summary> 168 /// 控制台数据错误 169 /// </summary> 170 /// <param name="ex"></param> 171 public static void WriteConsole(Exception ex) 172 { 173 Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); 174 Console.WriteLine("Data:" + ex.Data + Environment.NewLine 175 + " InnerException:" + ex.InnerException + Environment.NewLine 176 + " Message:" + ex.Message + Environment.NewLine 177 + " Source:" + ex.Source + Environment.NewLine 178 + " StackTrace:" + ex.StackTrace + Environment.NewLine 179 + " TargetSite:" + ex.TargetSite); 180 } 181 /// <summary> 182 /// 错误记录 183 /// </summary> 184 /// <param name="ex"></param> 185 public static void WriteLog(Exception ex) 186 { 187 WriteLog(ex,null); 188 } 189 /// <summary> 190 /// 错误记录 191 /// </summary> 192 /// <param name="ex">错误信息</param> 193 /// <param name="appendInfo">追加信息</param> 194 public static void WriteLog(Exception ex, string appendInfo) { 195 if (string.IsNullOrEmpty(appendInfo)) 196 { 197 WriteLog("Data:" + ex.Data + Environment.NewLine 198 + " InnerException:" + ex.InnerException + Environment.NewLine 199 + " Message:" + ex.Message + Environment.NewLine 200 + " Source:" + ex.Source + Environment.NewLine 201 + " StackTrace:" + ex.StackTrace + Environment.NewLine 202 + " TargetSite:" + ex.TargetSite); 203 } 204 else { 205 WriteLog("Data:" + ex.Data + Environment.NewLine 206 + " InnerException:" + ex.InnerException + Environment.NewLine 207 + " Message:" + ex.Message + Environment.NewLine 208 + " Source:" + ex.Source + Environment.NewLine 209 + " StackTrace:" + ex.StackTrace + Environment.NewLine 210 + " TargetSite:" + ex.TargetSite + Environment.NewLine 211 + " appendInfo:" + appendInfo); 212 } 213 } 214 /// <summary> 215 /// 写log 216 /// </summary> 217 /// <param name="InfoStr"></param> 218 public static void WriteLog(string InfoStr) 219 { 220 WriteLog(InfoStr, AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "Log"); 221 } 222 /// <summary> 223 /// 写log(自动时间log) 224 /// </summary> 225 /// <param name="InfoStr">内容</param> 226 /// <param name="FilePath">目录地址</param> 227 public static void WriteLog(string InfoStr, string DirPath) 228 { 229 WriteLog(InfoStr, DirPath, Encoding.UTF8); 230 } 231 /// <summary> 232 /// 写log(自动时间log) 233 /// </summary> 234 /// <param name="InfoStr">内容</param> 235 /// <param name="DirPath">目录地址</param> 236 /// <param name="encoding">编码</param> 237 public static void WriteLog(string InfoStr, string DirPath, Encoding encoding) 238 { 239 FileStream stream = null; 240 System.IO.StreamWriter writer = null; 241 try 242 { 243 string logPath = DirPath; 244 if (Directory.Exists(logPath) == false) 245 { 246 Directory.CreateDirectory(logPath); 247 } 248 string filepath = logPath + Path.DirectorySeparatorChar + "log_" + DateTime.Now.ToString("yyyyMMddHH") + ".txt"; 249 if (File.Exists(filepath) == false) 250 { 251 stream = new FileStream(filepath, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite); 252 } 253 else 254 { 255 stream = new FileStream(filepath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); 256 } 257 writer = new System.IO.StreamWriter(stream, encoding); 258 writer.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); 259 writer.WriteLine(InfoStr); 260 writer.WriteLine(""); 261 } 262 finally 263 { 264 if (writer != null) 265 { 266 //writer.Close(); 267 writer.Dispose(); 268 } 269 //if (stream != null) 270 //{ 271 // //stream.Close(); 272 // stream.Dispose(); 273 //} 274 } 275 } 276 277 /// <summary> 278 /// 写log到指定文件(不存在就创建) 279 /// </summary> 280 /// <param name="InfoStr">内容</param> 281 /// <param name="FilePath">文件地址</param> 282 public static void WriteLogToFile(string InfoStr, string FilePath) 283 { 284 WriteLogToFile(InfoStr, FilePath,Encoding.UTF8); 285 } 286 /// <summary> 287 /// 写log到指定文件(不存在就创建) 288 /// </summary> 289 /// <param name="InfoStr">内容</param> 290 /// <param name="FilePath">文件地址</param> 291 /// <param name="encoding">编码</param> 292 public static void WriteLogToFile(string InfoStr, string FilePath, Encoding encoding) 293 { 294 FileStream stream = null; 295 System.IO.StreamWriter writer = null; 296 try 297 { 298 string logPath = FilePath; 299 if (File.Exists(logPath) == false) 300 { 301 stream = new FileStream(logPath, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite); 302 } 303 else 304 { 305 stream = new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); 306 } 307 308 writer = new System.IO.StreamWriter(stream, encoding); 309 writer.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); 310 writer.WriteLine(InfoStr); 311 writer.WriteLine(""); 312 } 313 finally 314 { 315 if (writer != null) 316 { 317 //writer.Close(); 318 writer.Dispose(); 319 } 320 //if (stream != null) 321 //{ 322 // //stream.Close(); 323 // stream.Dispose(); 324 //} 325 } 326 } 327 /// <summary> 328 /// 写内容到指定文件(不存在就创建) 329 /// </summary> 330 /// <param name="InfoStr">内容</param> 331 /// <param name="FilePath">文件地址</param> 332 /// <param name="encoding">编码</param> 333 /// <param name="append">是否追加</param> 334 public static void WriteInfoToFile(string InfoStr, string FilePath, Encoding encoding,bool append) 335 { 336 FileStream stream = null; 337 System.IO.StreamWriter writer = null; 338 try 339 { 340 string logPath = FilePath; 341 if (File.Exists(logPath) == false) 342 { 343 stream = new FileStream(logPath, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite); 344 writer = new System.IO.StreamWriter(stream, encoding); 345 } 346 else 347 { 348 //存在就覆盖 349 writer = new System.IO.StreamWriter(logPath, append, encoding); 350 } 351 writer.Write(InfoStr); 352 } 353 finally 354 { 355 if (writer != null) 356 { 357 //writer.Close(); 358 writer.Dispose(); 359 } 360 //if (stream != null) 361 //{ 362 // //stream.Close(); 363 // stream.Dispose(); 364 //} 365 } 366 } 367 368 public static void AsyncWriteLog(byte[] datagram, string FilePath, AsyncCallback callback, int numBytes) 369 { 370 FileStream stream = null; 371 try 372 { 373 string logPath = FilePath; 374 if (File.Exists(logPath) == false) 375 { 376 stream = new FileStream(logPath, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite); 377 } 378 else 379 { 380 stream = new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); 381 } 382 383 if (stream.CanWrite) 384 { 385 386 stream.BeginWrite(datagram, 0, numBytes, callback, "AsyncWriteLog_" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); 387 } 388 else 389 { 390 throw new Exception("文件无法写入,文件或只读!"); 391 } 392 } 393 finally 394 { 395 if (stream != null) 396 { 397 //stream.Close(); 398 stream.Dispose(); 399 } 400 } 401 } 402 403 public static void AsyncWriteLog(byte[] datagram, string FilePath, int numBytes) 404 { 405 AsyncWriteLog(datagram, FilePath, new AsyncCallback(AsyncCallbackFunc), numBytes); 406 } 407 public static void AsyncCallbackFunc(IAsyncResult result) 408 { 409 FileStream filestream = result.AsyncState as FileStream; 410 filestream.EndWrite(result); 411 filestream.Close(); 412 } 413 414 /// <summary> 415 /// 文本转义(方便讲文本转换成C#变量代码) 416 /// 例子 " 转化成 string str="\""; 417 /// </summary> 418 /// <param name="str"></param> 419 /// <returns></returns> 420 public static string ToEscape(string str, string m_var) 421 { 422 /* 423 " \" 424 \ \425 */ 426 str = str.Trim(); 427 str = str.Replace("\\", "\\\\"); 428 str = str.Replace("\"", "\\\""); 429 return "string " + m_var + "=\"" + str + "\";"; 430 } 431 /// <summary> 432 /// 读取Appliction目录下的文件 433 /// </summary> 434 /// <param name="filePath"></param> 435 /// <param name="enc"></param> 436 /// <returns></returns> 437 public static string AppReadTxt(string filePath, Encoding enc) 438 { 439 FileStream stream = null; 440 System.IO.StreamReader reader = null; 441 string result = ""; 442 try 443 { 444 string appPath = AppDomain.CurrentDomain.BaseDirectory; 445 string path = appPath + filePath; 446 if (File.Exists(path) == false) 447 { 448 stream = new FileStream(path, FileMode.CreateNew, FileAccess.Read, FileShare.ReadWrite); 449 } 450 else 451 { 452 stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); 453 } 454 reader = new System.IO.StreamReader(stream, enc); 455 result =reader.ReadToEnd(); 456 } 457 catch (Exception e) 458 { 459 WriteLog(e); 460 } 461 finally 462 { 463 if (reader != null) 464 { 465 //reader.Close(); 466 reader.Dispose(); 467 } 468 //if (stream != null) 469 //{ 470 // //stream.Close(); 471 // stream.Dispose(); 472 //} 473 } 474 return result; 475 } 476 /// <summary> 477 /// 读取Appliction目录下的文件(UTF-8) 478 /// </summary> 479 /// <param name="filePath"></param> 480 /// <returns></returns> 481 public static string AppReadTxt(string filePath) 482 { 483 return AppReadTxt(filePath, System.Text.Encoding.UTF8); 484 } 485 }
常用IO操作类
1 /// <summary> 2 /// Json操作 3 /// </summary> 4 public static class Json 5 { 6 public static object ToJson(this string Json) 7 { 8 return Json == null ? null : JsonConvert.DeserializeObject(Json); 9 } 10 public static string ToJson(this object obj) 11 { 12 var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }; 13 return JsonConvert.SerializeObject(obj, timeConverter); 14 } 15 public static string ToJson(this object obj, string datetimeformats) 16 { 17 var timeConverter = new IsoDateTimeConverter { DateTimeFormat = datetimeformats }; 18 return JsonConvert.SerializeObject(obj, timeConverter); 19 } 20 public static T ToObject<T>(this string Json) 21 { 22 return Json == null ? default(T) : JsonConvert.DeserializeObject<T>(Json); 23 } 24 public static List<T> ToList<T>(this string Json) 25 { 26 return Json == null ? null : JsonConvert.DeserializeObject<List<T>>(Json); 27 } 28 public static DataTable ToTable(this string Json) 29 { 30 return Json == null ? null : JsonConvert.DeserializeObject<DataTable>(Json); 31 } 32 public static JObject ToJObject(this string Json) 33 { 34 return Json == null ? JObject.Parse("{}") : JObject.Parse(Json.Replace(" ", "")); 35 } 36 }
Json操作
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Runtime.InteropServices; 5 using System.Text; 6 using log4net; 7 8 9 10 //注意下面的语句一定要加上,指定log4net使用.config文件来读取配置信息(注入Log4Net配置信息,Log4Net的核心就在此) 11 [assembly: log4net.Config.XmlConfigurator(Watch = true)] 12 namespace OAMS.Common 13 { 14 public class LogHelper 15 { 16 #region 错误级别(目前只用这个) 17 /// <summary> 18 /// 错误日志 19 /// </summary> 20 /// <param name="t">注册类型,一般是异常所在类,也可以是异常本身类型</param> 21 /// <param name="ex">异常对象</param> 22 /// <param name="message">自定义消息(可选)</param> 23 public static void WriteErrorLog(Type t, Exception ex,params string[] message) 24 { 25 if (message.Length > 0) 26 { 27 ILog log = LogManager.GetLogger(t); 28 log.Error(message,ex); 29 } 30 else 31 { 32 ILog log = LogManager.GetLogger(t); 33 log.Error(ex); 34 } 35 } 36 37 /// <summary> 38 /// 错误日志 39 /// </summary> 40 public static void WriteErrorLog(Type t, string error) 41 { 42 ILog log = LogManager.GetLogger(t); 43 log.Error(error); 44 } 45 #endregion 46 47 #region 严重错误级别 48 /// <summary> 49 /// 严重错误日志 50 /// </summary> 51 public static void WriteFatalLog(Type t, Exception ex) 52 { 53 ILog log = LogManager.GetLogger(t); 54 log.Fatal(ex); 55 } 56 57 /// <summary> 58 /// 严重错误日志 59 /// </summary> 60 public static void WriteFatalLog(Type t, string fatal) 61 { 62 ILog log = LogManager.GetLogger(t); 63 log.Fatal(fatal); 64 } 65 #endregion 66 67 #region 信息级别 68 /// <summary> 69 /// 信息日志 70 /// </summary> 71 public static void WriteInfoLog(Type t, Exception ex) 72 { 73 ILog log = LogManager.GetLogger(t); 74 log.Info(ex); 75 } 76 77 /// <summary> 78 /// 信息日志 79 /// </summary> 80 public static void WriteInfoLog(Type t, string info) 81 { 82 ILog log = LogManager.GetLogger(t); 83 log.Info(info); 84 } 85 #endregion 86 87 #region 调试级别 88 /// <summary> 89 /// 调试日志 90 /// </summary> 91 public static void WriteDebugLog(Type t, Exception ex) 92 { 93 ILog log = LogManager.GetLogger(t); 94 log.Debug(ex); 95 } 96 97 /// <summary> 98 /// 调试日志 99 /// </summary> 100 public static void WriteDebugLog(Type t, string debug) 101 { 102 ILog log = LogManager.GetLogger(t); 103 log.Debug(debug); 104 } 105 #endregion 106 107 #region 警告级别 108 /// <summary> 109 /// 警告日志 110 /// </summary> 111 public static void WriteWarnLog(Type t, Exception ex) 112 { 113 ILog log = LogManager.GetLogger(t); 114 log.Warn(ex); 115 } 116 117 /// <summary> 118 /// 警告日志 119 /// </summary> 120 public static void WriteWarnLog(Type t, string warn) 121 { 122 ILog log = LogManager.GetLogger(t); 123 log.Warn(warn); 124 } 125 #endregion 126 127 } 128 }
log4net
1 public class StringHelper 2 { 3 /// <summary> 4 /// 获取Guid字符串值 5 /// </summary> 6 /// <returns></returns> 7 public static string GetGuidString() 8 { 9 /* 10 * Guid.NewGuid().ToString("N") 结果为: 11 38bddf48f43c48588e0d78761eaa1ce6 12 Guid.NewGuid().ToString("D") 结果为: 13 57d99d89-caab-482a-a0e9-a0a803eed3ba 14 Guid.NewGuid().ToString("B") 结果为: 15 {09f140d5-af72-44ba-a763-c861304b46f8} 16 Guid.NewGuid().ToString("P") 结果为: 17 (778406c2-efff-4262-ab03-70a77d09c2b5) 18 */ 19 return Guid.NewGuid().ToString("N"); 20 } 21 22 23 24 /// <summary> 25 /// 把字符串按照指定分隔符装成 List 去除重复 26 /// </summary> 27 /// <param name="oStr"></param> 28 /// <param name="sepeater"></param> 29 /// <returns></returns> 30 public static List<string> GetSubStringList(string oStr, char sepeater) 31 { 32 var ss = oStr.Split(sepeater); 33 return ss.Where(s => !string.IsNullOrEmpty(s) && s != sepeater.ToString(CultureInfo.InvariantCulture)).ToList(); 34 } 35 36 /// <summary> 37 /// 得到字符串长度,一个汉字长度为2 38 /// </summary> 39 /// <param name="inputString">参数字符串</param> 40 /// <returns></returns> 41 public static int StrLength(string inputString) 42 { 43 var ascii = new ASCIIEncoding(); 44 var tempLen = 0; 45 var s = ascii.GetBytes(inputString); 46 foreach (var t in s) 47 { 48 if (t == 63) 49 tempLen += 2; 50 else 51 tempLen += 1; 52 } 53 return tempLen; 54 } 55 56 /// <summary> 57 /// 截取指定长度字符串 58 /// </summary> 59 /// <param name="inputString">要处理的字符串</param> 60 /// <param name="len">指定长度</param> 61 /// <returns>返回处理后的字符串</returns> 62 public static string CutString(string inputString, int len) 63 { 64 var isShowFix = false; 65 if (len % 2 == 1) 66 { 67 isShowFix = true; 68 len--; 69 } 70 var ascii = new ASCIIEncoding(); 71 var tempLen = 0; 72 var tempString = ""; 73 var s = ascii.GetBytes(inputString); 74 for (var i = 0; i < s.Length; i++) 75 { 76 if (s[i] == 63) 77 tempLen += 2; 78 else 79 tempLen += 1; 80 81 try 82 { 83 tempString += inputString.Substring(i, 1); 84 } 85 catch 86 { 87 break; 88 } 89 90 if (tempLen > len) 91 break; 92 } 93 94 var mybyte = Encoding.Default.GetBytes(inputString); 95 if (isShowFix && mybyte.Length > len) 96 tempString += "…"; 97 return tempString; 98 } 99 100 /// <summary> 101 /// 删除字符串结尾的指定字符后的字符 102 /// </summary> 103 public static string DelLastChar(string str, string strchar) 104 { 105 return str.Substring(0, str.LastIndexOf(strchar, StringComparison.Ordinal)); 106 } 107 108 /// <summary> 109 /// 生成指定长度随机字符串(默认为6) 110 /// </summary> 111 /// <param name="codeCount"></param> 112 /// <returns></returns> 113 public static string GetRandomString(int codeCount = 6) 114 { 115 var str = string.Empty; 116 var rep = 0; 117 var num2 = DateTime.Now.Ticks + rep; 118 rep++; 119 var random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep))); 120 for (var i = 0; i < codeCount; i++) 121 { 122 char ch; 123 var num = random.Next(); 124 if ((num % 2) == 0) 125 { 126 ch = (char)(0x30 + ((ushort)(num % 10))); 127 } 128 else 129 { 130 ch = (char)(0x41 + ((ushort)(num % 0x1a))); 131 } 132 str = str + ch; 133 } 134 return str; 135 } 136 137 /// <summary> 138 /// 获取时间戳 139 /// </summary> 140 /// <returns></returns> 141 public static string GetTimeStamp() 142 { 143 TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); 144 return Convert.ToInt64(ts.TotalSeconds).ToString(); 145 } 146 /// <summary> 147 /// 过滤html 148 /// </summary> 149 /// <param name="HTMLStr"></param> 150 /// <returns></returns> 151 public static string FilterHTML(string HTMLStr) 152 { 153 if (!string.IsNullOrEmpty(HTMLStr)) 154 return System.Text.RegularExpressions.Regex.Replace(HTMLStr, "<[^>]*>| ", ""); 155 else 156 return ""; 157 } 158 }
StringHelper
1 public static class DataHelper 2 { 3 /// <summary> 4 /// js 序列化器 5 /// </summary> 6 static JavaScriptSerializer jss = new JavaScriptSerializer(); 7 8 /// <summary> 9 /// 将 对象 转成 json格式字符串 10 /// </summary> 11 /// <param name="obj"></param> 12 /// <returns></returns> 13 public static string Obj2Json(object obj) 14 { 15 //把集合 转成 json 数组格式字符串 16 return jss.Serialize(obj); 17 } 18 19 20 public static string ConvertTime(TimeSpan ts) 21 { 22 if (ts.TotalDays >= 365) 23 { 24 return Math.Floor(ts.TotalDays / 365) + "年前"; 25 } 26 else if (ts.TotalDays >= 30) 27 { 28 return Math.Floor(ts.TotalDays / 30) + "月前"; 29 } 30 else if (ts.TotalDays >= 1) 31 { 32 return Math.Floor(ts.TotalDays) + "天前"; 33 } 34 else if (ts.TotalHours >= 1) 35 { 36 return Math.Floor(ts.TotalHours) + "小时前"; 37 } 38 else if (ts.TotalMinutes >= 1) 39 { 40 return Math.Floor(ts.TotalHours) + "分钟前"; 41 } 42 else 43 { 44 return "刚刚"; 45 } 46 } 47 48 public static void SendEmail(string toEmail, string subject, string body) 49 { 50 string SmtpFrom = ConfigurationManager.AppSettings["SmtpFrom"]; 51 string SmtpSever = ConfigurationManager.AppSettings["SmtpSever"]; 52 string SmtpSeverPwd = ConfigurationManager.AppSettings["SmtpSeverPwd"]; 53 string SmtpUserName = ConfigurationManager.AppSettings["SmtpUserName"]; 54 55 System.Net.Mail.MailMessage mailObj = new System.Net.Mail.MailMessage(); 56 mailObj.From = new MailAddress(SmtpFrom); //发送人邮箱地址 57 mailObj.To.Add(toEmail); //收件人邮箱地址 58 mailObj.Subject = subject; //主题 59 mailObj.Body = body; //正文 60 mailObj.IsBodyHtml = true; 61 SmtpClient smtp = new SmtpClient(); 62 smtp.Host = SmtpSever; //smtp服务器名称 63 smtp.UseDefaultCredentials = true; 64 smtp.Credentials = new NetworkCredential(SmtpUserName, SmtpSeverPwd); //发送人的登录名和密码 65 smtp.Send(mailObj); 66 } 67 68 public static string SendMessage() 69 { 70 string ret = null; 71 72 CCPRestSDK.CCPRestSDK api = new CCPRestSDK.CCPRestSDK(); 73 //ip格式如下,不带https:// 74 bool isInit = api.init("app.cloopen.com", "8883"); 75 api.setAccount("8a216da862a4b4880162a58dc448007a", "16b1bc67b9814d718dd0a54ed6015296"); 76 api.setAppId("8a216da862a4b4880162a5931fc20083"); 77 Random rd = new Random(); 78 int num = rd.Next(100000, 1000000); 79 string result = ""; 80 try 81 { 82 if (isInit) 83 { 84 Dictionary<string, object> retData = api.SendTemplateSMS("18437963713", "1", new string[] { num.ToString(), "30" }); 85 ret = getDictionaryData(retData); 86 result = num.ToString(); 87 88 } 89 else 90 { 91 ret = "初始化失败"; 92 result = "失败"; 93 } 94 } 95 catch (Exception exc) 96 { 97 ret = exc.Message; 98 result = "失败"; 99 100 } 101 return result; 102 103 } 104 105 private static string getDictionaryData(Dictionary<string, object> data) 106 { 107 string ret = null; 108 foreach (KeyValuePair<string, object> item in data) 109 { 110 if (item.Value != null && item.Value.GetType() == typeof(Dictionary<string, object>)) 111 { 112 ret += item.Key.ToString() + "={"; 113 ret += getDictionaryData((Dictionary<string, object>)item.Value); 114 ret += "};"; 115 } 116 else 117 { 118 ret += item.Key.ToString() + "=" + (item.Value == null ? "null" : item.Value.ToString()) + ";"; 119 } 120 } 121 return ret; 122 } 123 124 125 }
DataHelper
1 public class MemcacheHelper 2 { 3 private static readonly MemcachedClient mc = null; 4 static MemcacheHelper() 5 { 6 //最好放在配置文件中 7 string[] serverlist = { "127.0.0.1:11211", "10.0.0.132:11211" }; 8 //初始化池 9 SockIOPool pool = SockIOPool.GetInstance(); 10 pool.SetServers(serverlist); 11 12 pool.InitConnections = 3; 13 pool.MinConnections = 3; 14 pool.MaxConnections = 5; 15 16 pool.SocketConnectTimeout = 1000; 17 pool.SocketTimeout = 3000; 18 19 pool.MaintenanceSleep = 30; 20 pool.Failover = true; 21 22 pool.Nagle = false; 23 pool.Initialize(); 24 25 // 获得客户端实例 26 mc = new MemcachedClient(); 27 mc.EnableCompression = false; 28 } 29 30 /// <summary> 31 /// 存储数据 32 /// </summary> 33 /// <param name="key"></param> 34 /// <param name="value"></param> 35 /// <returns></returns> 36 public static bool Set(string key, object value) 37 { 38 return mc.Set(key, value); 39 } 40 public static bool Set(string key, object value, DateTime time) 41 { 42 return mc.Set(key, value, time); 43 } 44 /// <summary> 45 /// 获取数据 46 /// </summary> 47 /// <param name="key"></param> 48 /// <returns></returns> 49 public static object Get(string key) 50 { 51 return mc.Get(key); 52 } 53 /// <summary> 54 /// 删除 55 /// </summary> 56 /// <param name="key"></param> 57 /// <returns></returns> 58 public static bool Delete(string key) 59 { 60 if (mc.KeyExists(key)) 61 { 62 return mc.Delete(key); 63 64 } 65 return false; 66 67 } 68 }
MemcacheHelper
1 public class SerializeHelper 2 { 3 /// <summary> 4 /// 对数据进行序列化 5 /// </summary> 6 /// <param name="value"></param> 7 /// <returns></returns> 8 public static string SerializeToString(object value) 9 { 10 return JsonConvert.SerializeObject(value); 11 } 12 /// <summary> 13 /// 反序列化操作 14 /// </summary> 15 /// <typeparam name="T"></typeparam> 16 /// <param name="str"></param> 17 /// <returns></returns> 18 public static T DeserializeToObject<T>(string str) 19 { 20 return JsonConvert.DeserializeObject<T>(str); 21 } 22 }
SerializeHelper
1 public class ValidateCode 2 { 3 public ValidateCode() 4 { 5 } 6 /// <summary> 7 /// 验证码的最大长度 8 /// </summary> 9 public int MaxLength 10 { 11 get { return 10; } 12 } 13 /// <summary> 14 /// 验证码的最小长度 15 /// </summary> 16 public int MinLength 17 { 18 get { return 1; } 19 } 20 21 /// <summary> 22 /// 生成验证码 23 /// </summary> 24 /// <param name="length">指定验证码的长度</param> 25 /// <returns></returns> 26 public string CreateValidateCode(int length) 27 { 28 int[] randMembers = new int[length]; 29 int[] validateNums = new int[length]; 30 string validateNumberStr = ""; 31 //生成起始序列值 32 int seekSeek = unchecked((int)DateTime.Now.Ticks); 33 Random seekRand = new Random(seekSeek); 34 int beginSeek = (int)seekRand.Next(0, Int32.MaxValue - length * 10000); 35 int[] seeks = new int[length]; 36 for (int i = 0; i < length; i++) 37 { 38 beginSeek += 10000; 39 seeks[i] = beginSeek; 40 } 41 //生成随机数字 42 for (int i = 0; i < length; i++) 43 { 44 Random rand = new Random(seeks[i]); 45 int pownum = 1 * (int)Math.Pow(10, length); 46 randMembers[i] = rand.Next(pownum, Int32.MaxValue); 47 } 48 //抽取随机数字 49 for (int i = 0; i < length; i++) 50 { 51 string numStr = randMembers[i].ToString(); 52 int numLength = numStr.Length; 53 Random rand = new Random(); 54 int numPosition = rand.Next(0, numLength - 1); 55 validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1)); 56 } 57 //生成验证码 58 for (int i = 0; i < length; i++) 59 { 60 validateNumberStr += validateNums[i].ToString(); 61 } 62 return validateNumberStr; 63 } 64 65 /// <summary> 66 /// 创建验证码的图片 67 /// </summary> 68 /// <param name="context">要输出到的page对象</param> 69 /// <param name="validateNum">验证码</param> 70 public void CreateValidateGraphic(string validateCode, HttpContext context) 71 { 72 Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22); 73 Graphics g = Graphics.FromImage(image); 74 try 75 { 76 //生成随机生成器 77 Random random = new Random(); 78 //清空图片背景色 79 g.Clear(Color.White); 80 //画图片的干扰线 81 for (int i = 0; i < 25; i++) 82 { 83 int x1 = random.Next(image.Width); 84 int x2 = random.Next(image.Width); 85 int y1 = random.Next(image.Height); 86 int y2 = random.Next(image.Height); 87 g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); 88 } 89 Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic)); 90 LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), 91 Color.Blue, Color.DarkRed, 1.2f, true); 92 g.DrawString(validateCode, font, brush, 3, 2); 93 //画图片的前景干扰点 94 for (int i = 0; i < 100; i++) 95 { 96 int x = random.Next(image.Width); 97 int y = random.Next(image.Height); 98 image.SetPixel(x, y, Color.FromArgb(random.Next())); 99 } 100 //画图片的边框线 101 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); 102 //保存图片数据 103 MemoryStream stream = new MemoryStream(); 104 image.Save(stream, ImageFormat.Jpeg); 105 //输出图片流 106 context.Response.Clear(); 107 context.Response.ContentType = "image/jpeg"; 108 context.Response.BinaryWrite(stream.ToArray()); 109 } 110 finally 111 { 112 g.Dispose(); 113 image.Dispose(); 114 } 115 } 116 117 /// <summary> 118 /// 得到验证码图片的长度 119 /// </summary> 120 /// <param name="validateNumLength">验证码的长度</param> 121 /// <returns></returns> 122 public static int GetImageWidth(int validateNumLength) 123 { 124 return (int)(validateNumLength * 12.0); 125 } 126 /// <summary> 127 /// 得到验证码的高度 128 /// </summary> 129 /// <returns></returns> 130 public static double GetImageHeight() 131 { 132 return 22.5; 133 } 134 135 136 137 //C# MVC 升级版 138 /// <summary> 139 /// 创建验证码的图片 140 /// </summary> 141 /// <param name="containsPage">要输出到的page对象</param> 142 /// <param name="validateNum">验证码</param> 143 public byte[] CreateValidateGraphic(string validateCode) 144 { 145 Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22); 146 Graphics g = Graphics.FromImage(image); 147 try 148 { 149 //生成随机生成器 150 Random random = new Random(); 151 //清空图片背景色 152 g.Clear(Color.White); 153 //画图片的干扰线 154 for (int i = 0; i < 25; i++) 155 { 156 int x1 = random.Next(image.Width); 157 int x2 = random.Next(image.Width); 158 int y1 = random.Next(image.Height); 159 int y2 = random.Next(image.Height); 160 g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); 161 } 162 Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic)); 163 LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), 164 Color.Blue, Color.DarkRed, 1.2f, true); 165 g.DrawString(validateCode, font, brush, 3, 2); 166 //画图片的前景干扰点 167 for (int i = 0; i < 100; i++) 168 { 169 int x = random.Next(image.Width); 170 int y = random.Next(image.Height); 171 image.SetPixel(x, y, Color.FromArgb(random.Next())); 172 } 173 //画图片的边框线 174 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); 175 //保存图片数据 176 MemoryStream stream = new MemoryStream(); 177 image.Save(stream, ImageFormat.Jpeg); 178 //输出图片流 179 return stream.ToArray(); 180 } 181 finally 182 { 183 g.Dispose(); 184 image.Dispose(); 185 } 186 } 187 188 }
ValidateCode
原文地址:https://www.cnblogs.com/ZkbFighting/p/8971300.html
时间: 2024-10-14 19:44:37