C# 常用的工具类
编码解码、图片与byte[]、日志文件写入和读取
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /// <summary> 2 /// 将字符串编码为Base64字符串 3 /// </summary> 4 /// <param name="str"></param> 5 /// <returns></returns> 6 public static string Base64Encode(string str) 7 { 8 byte[] barray; 9 barray = Encoding.Default.GetBytes(str); 10 return Convert.ToBase64String(barray); 11 } 12 13 /// <summary> 14 /// 将Base64字符串解码为普通字符串 15 /// </summary> 16 /// <param name="str"></param> 17 /// <returns></returns> 18 public static string Base64Decode(string str) 19 { 20 byte[] barray; 21 22 try 23 { 24 barray = Convert.FromBase64String(str); 25 return Encoding.Default.GetString(barray); 26 } 27 28 catch 29 { 30 return str; 31 } 32 33 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /// <summary> 2 /// 图片 转换 byte数组 3 /// </summary> 4 /// <param name="pic"></param> 5 /// <param name="fmt"></param> 6 /// <returns></returns> 7 public static byte[] image_Image2Byte(System.Drawing.Image pic, System.Drawing.Imaging.ImageFormat fmt) 8 { 9 MemoryStream mem = new MemoryStream(); 10 pic.Save(mem, fmt); 11 mem.Flush(); 12 return mem.ToArray(); 13 } 14 15 /// <summary> 16 /// byte数组 转换 图片 17 /// </summary> 18 /// <param name="bytes"></param> 19 /// <returns></returns> 20 public static System.Drawing.Image image_Byte2Image(byte[] bytes) 21 { 22 MemoryStream mem = new MemoryStream(bytes, true); 23 mem.Read(bytes, 0, bytes.Length); 24 mem.Flush(); 25 System.Drawing.Image aa = System.Drawing.Image.FromStream(mem, true); 26 mem.Close(); 27 28 return aa; 29 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /// <summary> 2 /// ip 转换 长整型 3 /// </summary> 4 /// <param name="strIP"></param> 5 /// <returns></returns> 6 public static long IP2Long(string strIP) 7 { 8 long[] ip = new long[4]; 9 string[] s = strIP.Split('.'); 10 ip[0] = long.Parse(s[0]); 11 ip[1] = long.Parse(s[1]); 12 ip[2] = long.Parse(s[2]); 13 ip[3] = long.Parse(s[3]); 14 15 return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3]; 16 } 17 18 19 /// <summary> 20 /// 长整型 转换 IP 21 /// </summary> 22 /// <param name="longIP"></param> 23 /// <returns></returns> 24 public static string Long2IP(long longIP) 25 { 26 StringBuilder sb = new StringBuilder(""); 27 sb.Append(longIP >> 24); 28 sb.Append("."); 29 30 //将高8位置0,然后右移16为 31 sb.Append((longIP & 0x00FFFFFF) >> 16); 32 sb.Append("."); 33 34 sb.Append((longIP & 0x0000FFFF) >> 8); 35 sb.Append("."); 36 37 38 sb.Append((longIP & 0x000000FF)); 39 40 return sb.ToString(); 41 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /// <summary> 2 /// 获取CPU的序列号 3 /// </summary> 4 /// <returns></returns> 5 public static string GetCpuNum() 6 { 7 8 string cpuInfo = ""; 9 10 ManagementClass cimobject = new ManagementClass("Win32_Processor"); 11 12 ManagementObjectCollection moc = cimobject.GetInstances(); 13 14 foreach (ManagementObject mo in moc) 15 16 { 17 18 cpuInfo = mo.Properties["ProcessorId"].Value.ToString(); 19 20 } 21 22 return cpuInfo; 23 24 } 25 26 27 28 /// <summary> 29 /// 获取硬盘ID号 30 /// </summary> 31 /// <returns></returns> 32 public static string GetHardDiskNum() 33 { 34 35 string HDid = ""; 36 37 ManagementClass cimobject = new ManagementClass("Win32_DiskDrive"); 38 39 ManagementObjectCollection moc = cimobject.GetInstances(); 40 41 foreach (ManagementObject mo in moc) 42 43 { 44 45 HDid = (string)mo.Properties["Model"].Value; 46 47 } 48 49 return HDid; 50 51 } 52 53 54 55 /// <summary> 56 /// 获取网卡MacAddress 57 /// </summary> 58 /// <returns></returns> 59 public static string GetNetCardNum() 60 { 61 62 string NCid = ""; 63 64 ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); 65 66 ManagementObjectCollection moc = mc.GetInstances(); 67 68 foreach (ManagementObject mo in moc) 69 70 { 71 72 if ((bool)mo["IPEnabled"] == true) 73 74 NCid = mo["MacAddress"].ToString(); 75 76 mo.Dispose(); 77 78 } 79 80 return NCid; 81 82 } 83 84 85 86 /// <summary> 87 /// 是否ping通 88 /// </summary> 89 /// <param name="ip"></param> 90 /// <param name="timeout">毫秒</param> 91 /// <returns></returns> 92 public static bool ping(string ip, int timeout) 93 { 94 95 IPAddress ipadd; 96 97 if (!IPAddress.TryParse(ip, out ipadd)) 98 99 { 100 101 return false; 102 103 } 104 105 Ping pingSender = new Ping(); 106 107 PingReply reply = pingSender.Send(ip, timeout, new Byte[] { Convert.ToByte(1) }); 108 109 if (reply.Status == IPStatus.Success) 110 111 return true; 112 113 else 114 115 return false; 116 117 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /// <summary> 2 /// 文件是否存在 3 /// </summary> 4 /// <param name="filename"></param> 5 /// <returns></returns> 6 public static bool IsFileExists(string filename) 7 { 8 9 return System.IO.File.Exists(filename); 10 11 } 12 13 14 /// <summary> 15 /// 写入日志文件[记录异常等重要信息] 16 /// </summary> 17 /// <param name="sPath"></param> 18 /// <param name="sFileName"></param> 19 /// <param name="content"></param> 20 /// <returns></returns> 21 public static bool WriteLog(string sPath, string sFileName, string content) 22 { 23 24 try 25 26 { 27 28 StreamWriter sr; 29 30 if (!Directory.Exists(sPath)) { Directory.CreateDirectory(sPath); } 31 32 string v_filename = sPath + "\\" + sFileName; 33 34 35 36 if (!File.Exists(v_filename)) 37 38 { 39 40 sr = File.CreateText(v_filename); 41 42 sr.Close(); 43 44 } 45 46 using (FileStream fs = new FileStream(v_filename, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.Write)) 47 48 { 49 50 using (sr = new StreamWriter(fs)) 51 52 { 53 54 sr.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + content); 55 56 sr.Close(); 57 58 } 59 60 fs.Close(); 61 62 } 63 64 return true; 65 66 } 67 68 catch { return false; } 69 70 } 71 72 73 /// <summary> 74 /// 读取日志文件 75 /// </summary> 76 /// <param name="sFileName"></param> 77 /// <returns></returns> 78 public static ArrayList ReadFileRow(string sFileName) 79 { 80 81 string sLine = ""; 82 83 ArrayList list = null; 84 85 try 86 87 { 88 89 using (StreamReader reader = new StreamReader(sFileName)) 90 91 { 92 93 list = new ArrayList(); 94 95 96 97 while (!reader.EndOfStream) 98 99 { 100 101 sLine = reader.ReadLine(); 102 103 if (sLine != "") 104 105 { 106 107 list.Add(sLine.Trim()); 108 109 } 110 111 } 112 113 reader.Close(); 114 115 } 116 117 } 118 119 catch 120 121 { 122 123 124 125 } 126 127 return list; 128 129 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /// <summary> 2 /// 备份文件 3 /// </summary> 4 /// <param name="sourceFileName">源文件名</param> 5 /// <param name="destFileName">目标文件名</param> 6 /// <param name="overwrite">当目标文件存在时是否覆盖</param> 7 /// <returns>操作是否成功</returns> 8 public static bool BackupFile(string sourceFileName, string destFileName, bool overwrite) 9 { 10 11 if (!System.IO.File.Exists(sourceFileName)) 12 13 throw new FileNotFoundException(sourceFileName + "文件不存在!"); 14 15 16 17 if (!overwrite && System.IO.File.Exists(destFileName)) 18 19 return false; 20 21 22 23 try 24 25 { 26 27 System.IO.File.Copy(sourceFileName, destFileName, true); 28 29 return true; 30 31 } 32 33 catch (FileNotFoundException e) 34 35 { 36 37 throw e; 38 39 } 40 41 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /// <summary> 2 /// 字符串中是否包含汉字 3 /// </summary> 4 /// <param name="str"></param> 5 /// <returns></returns> 6 public static bool IsExistHanZi(string str) 7 8 { 9 10 Regex reg = new Regex(@"[\u4e00-\u9fa5]"); 11 12 return reg.IsMatch(str); 13 14 } 15 16 17 18 /// Email格式 19 /// </summary> 20 /// <param name="strEmail"></param> 21 /// <returns></returns> 22 public static bool IsValidEmail(string strEmail) 23 { 24 25 return Regex.IsMatch(strEmail, @"^[\w\.]+([-]\w+)*@[A-Za-z0-9-_]+[\.][A-Za-z0-9-_]"); 26 27 } 28 29 30 /// <summary> 31 /// 是否是安全的SQL语句 32 /// </summary> 33 /// <param name="str"></param> 34 /// <returns></returns> 35 public static bool IsSafeSqlString(string str) 36 { 37 38 return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']"); 39 40 }