using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Drawing; using System.Drawing.Imaging; using System.IO.Packaging; using System.Web; using System.IO.Compression; using System.Security.Cryptography; namespace Helpers { public static partial class Tool { /// /// 文件输出至指定路径 /// /// 文件物理路径,例:C:\test.txt /// 要输出的内容,以utf-8的格式 /// 输出结果 public static bool PrintTXTFile(string path, string content) { try { StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8); sw.WriteLine(content); sw.Close(); sw.Dispose(); return true; } catch (Exception ex) { Tool.PrintLog("添加内容失败", ex.Message); return false; } } /// /// 取得列表类别 /// /// type /// public static string GetType(int number) { string str = ""; switch (number) { case -1: str = "最新添加"; break; case 0: str = "学习路上"; break; case 1: str = "个人私文"; break; case 2: str = "加密"; break; case 3: str = "随笔记"; break; default: str = ""; break; } return str; } /// /// 无效字符清空 /// /// 待过滤的字符串 /// 要过滤的字符列表 /// 过滤掉无效内容后的字符串 public static string FilterStr(string str, List list) { if (string.IsNullOrWhiteSpace(str)) { return ""; } foreach (var a in list) { str = Helpers.Tool.ReplaceString(str, a, ""); } return str; } /// /// 处理html常见标签的字符串 /// /// 待处理的字符串 /// 处理后的字符串 public static string HtmlCodeStr(string str) { str = Helpers.Tool.ReplaceString(str, "", ""); str = Helpers.Tool.ReplaceString(str, "", "\f"); str = Helpers.Tool.ReplaceString(str, "", ""); str = Helpers.Tool.ReplaceString(str, "", "\n"); str = Helpers.Tool.ReplaceString(str, "", ""); str = Helpers.Tool.ReplaceString(str, "", "\n"); str = Helpers.Tool.ReplaceString(str, "
", ""); str = Helpers.Tool.ReplaceString(str, "
", "\n"); str = Helpers.Tool.ReplaceString(str, "

", "\r"); str = Helpers.Tool.ReplaceString(str, "

", "\r"); str = Helpers.Tool.ReplaceString(str, "
", "\r"); str = Helpers.Tool.ReplaceString(str, "", ""); str = Helpers.Tool.ReplaceString(str, "", ""); str = Helpers.Tool.ReplaceString(str, "", "\n"); str = Helpers.Tool.ReplaceString(str, "", "\n"); str = Helpers.Tool.ReplaceString(str, "", "\n"); str = Helpers.Tool.ReplaceString(str, "

", ""); str = Helpers.Tool.ReplaceString(str, "

", ""); str = Helpers.Tool.ReplaceString(str, "

", ""); str = Helpers.Tool.ReplaceString(str, "

", ""); str = Helpers.Tool.ReplaceString(str, "

", ""); str = Helpers.Tool.ReplaceString(str, "

", ""); str = Helpers.Tool.ReplaceString(str, "

", ""); str = Helpers.Tool.ReplaceString(str, "

", ""); str = Helpers.Tool.ReplaceString(str, "", ""); str = Helpers.Tool.ReplaceString(str, "", ""); str = Helpers.Tool.ReplaceString(str, ">", "<"); str = Helpers.Tool.ReplaceString(str, "<", ">"); str = Helpers.Tool.ReplaceString(str, " ", " "); str = Helpers.Tool.ReplaceString(str, "
", "\n\r"); str = Helpers.Tool.ReplaceString(str, "
", "\n\r"); str = Helpers.Tool.ReplaceString(str, "
", "\n\r"); str = Helpers.Tool.ReplaceString(str, "
", "\n\r"); str = Helpers.Tool.ReplaceString(str, "\"", ""); return str; } /// /// IPV4地址验证 /// /// public static bool IpAddressSign(string ip) { try { if (ip == "::1") { return true; } ip = ip.Trim(); string[] ips = ip.Split('.'); if (ips.Length != 4) { return false; } foreach (var a in ips) { int splitAddr = int.Parse(a); if (splitAddr < 0 && splitAddr > 256) { return false; } } return true; } catch { return false; } } /// /// 32位大写MD5加密 /// /// 待加密的字符串 /// public static string MD5(string str) { string result = MD5(str, true, 32); return result; } /// /// 32位MD5加密 /// /// 待加密的字符串 /// 是否大写 /// public static string MD5(string str, bool IsUpper) { string result = MD5(str, IsUpper, 32); return result; } /// /// MD5加密 /// /// 待加密的字符串 /// 是否大写 /// 加密位数16或者32 /// public static string MD5(string str, bool IsUpper, int bit) { System.Security.Cryptography.MD5 md = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] byteStream = System.Text.Encoding.UTF8.GetBytes(str); byte[] temp = md.ComputeHash(byteStream); StringBuilder tempStr = new StringBuilder(); string result = null; foreach (var a in temp) { tempStr.Append(a.ToString("x2")); } if (IsUpper) { result = tempStr.ToString().ToUpper(); } else { result = tempStr.ToString().ToLower(); } if (bit == 16) { result = result.Substring(8, 16); } else if (bit == 32) { result = result.ToString(); } else { result = string.Empty; } return result; } /// /// Sha256加密 /// /// /// public static string Sha256(string str) { byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(str); SHA256 sha256 = new SHA256CryptoServiceProvider(); byte[] retVal = sha256.ComputeHash(bytValue); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb.ToString().ToUpper(); } /// /// 验证身份证号格式 /// /// 身份证号 /// 正确或错误 public static bool ValidateIdentityCode(string code) { if (code.Length != 15 && code.Length != 18) { return false; } if (code[0] == 48) { return false; } foreach (char c in code) { if (c > 47 && c < 58) { continue; } else if (c == 88 || c == 120) { if (code[17] == c) { continue; } else { return false; } } else { return false; } } return true; } /// /// 验证手机号格式 /// /// 手机号 /// 正确或错误 public static bool ValidateMobile(string mobile) { if (mobile.Length != 11) { return false; } if (mobile[0] != 49) { return false; } foreach (char c in mobile) { if (c < 48 || c > 57) { return false; } } return true; } /// /// 验证邮箱格式 /// /// 邮箱账号 /// 正确或错误 public static bool ValidateMail(string mail) { if (mail.Length < 5) { return false; } //反转邮箱账号字符串 string descMail = null; foreach (char c in mail.Reverse()) { descMail += c; } int atindex = descMail.IndexOf('@'); int dotindex = descMail.IndexOf('.'); if (atindex < 3) { return false; } if (dotindex < 1) { return false; } if (mail[0] == '@' || mail[0] == '.') { return false; } if (dotindex > atindex) { return false; } return true; } /// /// 过滤非法Sql字符 /// /// /// public static string SQLFilter(string str) { if (string.IsNullOrEmpty(str)) { return ""; } List strs = new List(); strs.Add("'--"); strs.Add(";"); strs.Add("|"); return FilterStr(str, strs); } /// /// 图片转base64 /// /// /// public static string ImgToBase64String(Bitmap bmp) { try { MemoryStream ms = new MemoryStream(); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); ms.Close(); return Convert.ToBase64String(arr); } catch { return null; } } /// /// 图片转base64 /// /// 文件流 /// public static string ImgToBase64String(FileStream fs) { byte[] bytes = new byte[fs.Length]; fs.Read(bytes, 0, (int)fs.Length); string base64Str = Convert.ToBase64String(bytes); return base64Str; } /// /// base64保存成图片,返回Bitmap对象 /// /// public static Bitmap Base64StringToImage(string filePath, string fileName, string strbase64, ImageType type) { try { byte[] arr = Convert.FromBase64String(strbase64); MemoryStream ms = new MemoryStream(arr); Bitmap bmp = new Bitmap(ms); switch (type) { case ImageType.Jpg: bmp.Save($@"{filePath}\{fileName}.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); break; case ImageType.Bmp: bmp.Save($@"{filePath}\{fileName}.bmp", ImageFormat.Bmp); break; case ImageType.Gif: bmp.Save($@"{filePath}\{fileName}.gif", ImageFormat.Gif); break; case ImageType.Png: bmp.Save($@"{filePath}\{fileName}.png", ImageFormat.Png); break; default: bmp.Save($@"{filePath}\{fileName}.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); break; } //bmp.Save($@"{savePath}\test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); //bmp.Save(@"d:\"test.bmp", ImageFormat.Bmp); //bmp.Save(@"d:\"test.gif", ImageFormat.Gif); //bmp.Save(@"d:\"test.png", ImageFormat.Png); ms.Close(); return bmp; } catch (Exception ex) { Helpers.Tool.PrintLog_Error(ex.Message, ex.StackTrace); return null; } } /// /// 创建文件夹 /// /// 路径 /// 文件夹名 /// public static string CreateDirectory(string filePath, string folderName) { if (string.IsNullOrEmpty(filePath)) { if (string.IsNullOrEmpty(folderName)) { return ""; } } else { if (filePath.Substring(filePath.Length - 1) == @"\") { filePath = filePath.Substring(0, filePath.Length - 1); } } string path = filePath + @"\" + folderName; try { if (!System.IO.Directory.Exists(path)) { Directory.CreateDirectory(path); } } catch (Exception ex) { Helpers.Tool.PrintLog_Info("出错了!", ex.Message + ex.StackTrace); return null; } Helpers.Tool.PrintLog_Info(path, ""); return path; } /// /// 将时间转换成秒级的时间戳 /// /// 要转换的时间 /// public static int DateTimeToDateStr(DateTime time) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); int timeStr = (int)(DateTime.Now - startTime).TotalSeconds; return timeStr; } /// /// 将时间戳转换成C#的时间 /// /// /// public static DateTime DateStrToDateTime(int dateStr) { DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = long.Parse(dateStr.ToString() + "0000000"); TimeSpan toNow = new TimeSpan(lTime); return Tool.FormatDate(startTime.Add(toNow)); } /// /// 按字典的key升序拼接字典,字典key和value的类型为string /// /// /// public static string SplicingDic(Dictionary dic) { if (dic == null) { return null; } var temp = dic.OrderBy(o => o.Key, StringComparer.OrdinalIgnoreCase); StringBuilder result = new StringBuilder(); foreach (var a in temp) { result.Append($"{a.Key}={a.Value}&"); } string str = result.ToString(); str = str.Substring(0, str.Length - 1); return str; } /// /// ASE加密 /// /// 待加密的文本 /// 密钥(可选) /// 位移量(可选) /// 加密后的密文 public static string ASEEncode(string text, string key = "abcd", string iv = "dddd") { Helpers.ASEEncryption ase = new Helpers.ASEEncryption(); return ase.Encrypt(text, key, iv); } /// /// ASE解密 /// /// 密文 /// 密钥(可选) /// 位移量(可选) /// 解密后的文本 public static string ASEDecode(string pwdText, string key = "abcd", string iv = "dddd") { Helpers.ASEEncryption ase = new Helpers.ASEEncryption(); return ase.Decrypt(pwdText, key, iv); } /// /// 将指定的文件夹压缩成ZIP文件 /// /// 待压缩的文件夹路径 /// 压缩后的文件存放路径(含文件名,例C:\test.zip) /// 是否覆盖同名文件 /// [Obsolete("已弃用,此方法会在压缩包中自动创建了个文件", true)] public static bool PackageFolderZIP(string folderName, string compressedFileName, bool overrideExisting) { if (folderName.EndsWith(@"\")) folderName = folderName.Remove(folderName.Length - 1); bool result = false; if (!Directory.Exists(folderName)) { return result; } if (!overrideExisting && File.Exists(compressedFileName)) { return result; } try { using (Package package = Package.Open(compressedFileName, FileMode.Create)) { var fileList = Directory.EnumerateFiles(folderName, "*", SearchOption.AllDirectories); foreach (string fileName in fileList) { //The path in the package is all of the subfolders after folderName string pathInPackage; pathInPackage = Path.GetDirectoryName(fileName).Replace(folderName, string.Empty) + "/" + Path.GetFileName(fileName); Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(pathInPackage, UriKind.Relative)); PackagePart packagePartDocument = package.CreatePart(partUriDocument, "", CompressionOption.Maximum); using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { fileStream.CopyTo(packagePartDocument.GetStream()); } } } result = true; } catch (Exception e) { throw new Exception("Error zipping folder " + folderName, e); } return result; } /// /// 解压ZIP文件 /// /// 待解压的文件路径 /// 解压后存放的目录 /// 是否进行覆盖 /// public static bool UncompressFileZIP(string folderName, string compressedFileName, bool overrideExisting) { bool result = false; try { if (!File.Exists(compressedFileName)) { return result; } DirectoryInfo directoryInfo = new DirectoryInfo(folderName); if (!directoryInfo.Exists) directoryInfo.Create(); using (Package package = Package.Open(compressedFileName, FileMode.Open, FileAccess.Read)) { foreach (PackagePart packagePart in package.GetParts()) { ExtractPart(packagePart, folderName, overrideExisting); } } result = true; } catch (Exception e) { throw new Exception("Error unzipping file " + compressedFileName, e); } return result; } /// /// 将指定的文件夹压缩成ZIP文件 /// /// 待压缩的文件夹路径 /// 压缩后的文件存放路径(含文件名,例C:\test.zip) /// 是否覆盖同名文件 /// public static bool ZIPCompressFolder(string folderName, string compressedFileName, bool overrideExisting) { if (folderName.EndsWith(@"\")) folderName = folderName.Remove(folderName.Length - 1); bool result = false; if (!Directory.Exists(folderName)) { return result; } if (!overrideExisting && File.Exists(compressedFileName)) { return result; } if (File.Exists(compressedFileName)) { File.Delete(compressedFileName); } try { ZipFile.CreateFromDirectory(folderName, compressedFileName); return true; } catch (Exception ex) { return false; } } /// /// 将多个文件压缩成ZIP文件 /// /// 待压缩的文件路径列表 /// 压缩后的文件存放路径(含文件名,例C:\test.zip) /// 是否覆盖同名文件 /// 打包后移除的路径部分,示例格式: C:\Files\ /// public static bool ZIPCompressFiles(List fileList, string compressedFileName, bool overrideExisting,string replaceFolderName = "") { bool result = false; try { using (Package package = Package.Open(compressedFileName, FileMode.Create)) { Dictionary dic = new Dictionary(); foreach (string fileName in fileList) { if (!File.Exists(fileName)) { return result; } //The path in the package is all of the subfolders after folderName string pathInPackage; pathInPackage = Path.GetDirectoryName(fileName).Replace(replaceFolderName, string.Empty) + "/" + Path.GetFileName(fileName); if (dic.ContainsKey(pathInPackage)) { dic[pathInPackage] = dic[pathInPackage]++; int maxLen = Path.GetFileName(fileName).Length; if (Path.GetFileName(fileName).LastIndexOf(".") > -1) { maxLen = Path.GetFileName(fileName).LastIndexOf("."); } pathInPackage = Path.GetFileName(fileName).Substring(0, maxLen) + $"({dic[pathInPackage]})" + Path.GetFileName(fileName).Substring(maxLen); } else { dic.Add(pathInPackage, 0); } Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(pathInPackage, UriKind.Relative)); PackagePart packagePartDocument = package.CreatePart(partUriDocument, "", CompressionOption.Maximum); using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { fileStream.CopyTo(packagePartDocument.GetStream()); } } } result = true; } catch (Exception e) { throw new Exception("Error Directory : " + fileList.ToJson(), e); } return result; } /// /// 解压ZIP文件 /// /// 待解压的文件 /// 解压后存放的目录 /// public static bool UnZIPCompressFolder(string compressedFileName, string TofolderName) { bool result = false; if (!File.Exists(compressedFileName)) { throw new Exception("未找到相关文件"); } if (TofolderName.EndsWith(@"\")) { TofolderName = TofolderName.Remove(TofolderName.Length - 1); } CreateDirectory(TofolderName, ""); try { ZipFile.ExtractToDirectory(compressedFileName, TofolderName); return true; } catch (Exception ex) { return false; } } /// /// 密码加密 /// /// 账号 /// 密码 public static string EncryptPwd(string account, string pwd) { return Helpers.Tool.MD5(account + Helpers.Tool.MD5("Moli") + pwd); } /// /// 获取一个新的token /// public static string CreateToken(string key) { string time = DateTime.Now.ToString("yyyyMMddHHmmssfff"); string guid = Guid.NewGuid().ToString(); string param1 = "Moli"; string param2 = MD5(MD5(time) + Sha256(time) + param1 + Sha256(guid)); string p1 = Sha256(param2); string token = p1.Insert(Convert.ToInt32(time.Substring(12)) % p1.Length, MD5(time).Insert(Convert.ToInt32(time.Substring(12)) % MD5(time).Length, MD5(guid))) .Insert(Convert.ToInt32(time.Substring(12)) % p1.Length, Sha256(guid)); return key + token.Substring(20, token.Length - 30); } /// /// 将文件流的bytes长度转成相应的标准单位 /// /// 待转的长度,单位bytes /// 转换后的标准单位(B,KB,MB,GB,TB) public static string FileSizeChange(long BytesSize) { long maxSize = 1024; if (BytesSize < 1024) { return BytesSize.ToString() + "B"; } else if (BytesSize < maxSize * maxSize) { return Math.Round(Math.Ceiling(BytesSize * 1000 / 1024.00) / 1000.00, 3).ToString() + "KB"; } else if (BytesSize < maxSize * maxSize * maxSize) { return Math.Round(Math.Ceiling(BytesSize * 1000 / (1024.00 * 1024.00)) / 1000.00, 3).ToString() + "MB"; } else if (BytesSize < maxSize * maxSize * maxSize * maxSize) { return Math.Round(Math.Ceiling(BytesSize * 1000 / (1024.00 * 1024.00 * 1024.00)) / 1000.00, 3).ToString() + "GB"; } return Math.Round(Math.Ceiling(BytesSize * 1000 / (1024.00 * 1024.00 * 1024.00) / 1024.00) / 1000.00, 3).ToString() + "TB"; } /// /// 将文件流的bytes长度转成指定的标准单位 /// /// 待转的长度,单位bytes /// 转换后的单位 /// 转换后的长度(含单位) public static string FileSizeChange(long BytesSize, FileSizeUnit fileSizeUnit) { switch (fileSizeUnit) { case FileSizeUnit.Bytes: return BytesSize.ToString() + "B"; case FileSizeUnit.KB: return Math.Round(Math.Ceiling(BytesSize * 1000 / 1024.00) / 1000.00, 3).ToString() + "KB"; case FileSizeUnit.MB: return Math.Round(Math.Ceiling(BytesSize * 1000 / (1024.00 * 1024.00)) / 1000.00, 3).ToString() + "MB"; case FileSizeUnit.GB: return Math.Round(Math.Ceiling(BytesSize * 1000 / (1024.00 * 1024.00 * 1024.00)) / 1000.00, 3).ToString() + "GB"; case FileSizeUnit.TB: return Math.Round(Math.Ceiling(BytesSize * 1000 / (1024.00 * 1024.00 * 1024.00) / 1024.00) / 1000.00, 3).ToString() + "TB"; default: return FileSizeChange(BytesSize); } } /// /// 将带单位的大小换算成以Byte为单位的大小 /// /// 文件大小,含单位,示例数据:2.31MB /// 换算Byte成后的长度 public static long FileSizeChangeForByte(string sizeStr) { string unit = ""; long size = 0; int index = sizeStr.ToUpper().IndexOf("B"); if (index == -1) { throw new Exception("无效的单位字符"); } if (sizeStr[index - 1] > 71) { unit = sizeStr.Substring(index - 1); size = Convert.ToInt64(sizeStr.Substring(0, index - 1)); } return FileSizeChangeForByte(size, (FileSizeUnit)Enum.Parse(typeof(FileSizeUnit), unit)); } /// /// 将带单位的大小换算成以Byte为单位的大小 /// /// 文件大小,不含单位,示例数据:2.31 /// 文件大小单位 /// 换算Byte成后的长度 public static long FileSizeChangeForByte(double size, FileSizeUnit fileSizeUnit) { switch (fileSizeUnit) { case FileSizeUnit.Bytes: return Convert.ToInt64(size); case FileSizeUnit.KB: return Convert.ToInt64(size*1024); case FileSizeUnit.MB: return Convert.ToInt64(size * 1024 * 1024); case FileSizeUnit.GB: return Convert.ToInt64(size * 1024 * 1024 * 1024); case FileSizeUnit.TB: return Convert.ToInt64(size * 1024 * 1024 * 1024 * 1024); default: return Convert.ToInt64(size); } } /// /// 将Stream写入FileStream中并返回FileStream /// /// Stream对象 /// FileStream对象 /// 写入后的FileStream public static FileStream WriteFileStream(Stream s, FileStream fs) { using (BinaryWriter bw = new BinaryWriter(fs)) { bw.Write(s.ToByte()); return fs; } } /// /// 路径统一格式化 /// /// 待格式化的路径 /// 是否包含路径结束符'\',默认包含 /// 格式化后的路径 public static string GetRoot(string root,bool endChar = true) { if (string.IsNullOrWhiteSpace(root)) { return ""; } if (endChar) { if (root.EndsWith("\\")) { return root; } else { root += "\\"; return root; } } else { if (root.EndsWith("\\")) { root = root.Remove(root.Length - 1); return root; } else { return root; } } } /// /// 路径统一格式化 /// /// 待格式化的路径 /// 文件名 /// 格式化后的路径 public static string GetRoot(string root, string fileName) { if (string.IsNullOrWhiteSpace(root)) { return ""; } if (!root.EndsWith("\\")) { root += "\\"; } root += fileName; return root; } /// /// 通过完整的文件路径取得Etag /// /// File Full Name /// public static string GetEtag(string FileName) { if (!File.Exists(FileName)) { throw new Exception("找不到该文件"); } FileInfo fi = new FileInfo(FileName); Int64 FileSize = Convert.ToInt64(fi.OpenRead().Length); if (FileSize > Int64.MaxValue) { throw new Exception("文件过大!"); } return GetEtag(fi, FileSize); } /// /// 获取文件的Etag /// /// System.IO.FileInfo /// 文件Stream.leng /// public static string GetEtag(System.IO.FileInfo fi,Int64 FileSize) { string Etag = ""; Etag = MD5("Etag:" + fi.FullName + "----" + fi.LastWriteTimeUtc + "----" + FileSize, true); return Etag; } /// /// 检测文件路径中是否含有非法字符 /// /// /// public static bool ExistsFilePath(string path) { string[] s = "\\ : ( ? \" < > |".Split(" "); foreach (string a in s) { if (path.IndexOf(a) > -1) { return false; } } return true; } private static void ExtractPart(PackagePart packagePart, string targetDirectory, bool overrideExisting) { string stringPart = targetDirectory + HttpUtility.UrlDecode(packagePart.Uri.ToString()).Replace('\\', '/'); if (!Directory.Exists(Path.GetDirectoryName(stringPart))) Directory.CreateDirectory(Path.GetDirectoryName(stringPart)); if (!overrideExisting && File.Exists(stringPart)) return; using (FileStream fileStream = new FileStream(stringPart, FileMode.Create)) { packagePart.GetStream().CopyTo(fileStream); } } } /// /// 枚举图片格式 /// public enum ImageType { Jpg = 0, Bmp = 1, Gif = 2, Png = 3 } public enum FileSizeUnit { bit = 0, Bytes = 1, KB = 2, MB = 3, GB = 4, TB = 5, } }