C#实用函数积累
需要时Ctrl+F用关键字查找吧
using System; using System.Collections.Generic; using System.Text; using Microsoft.Win32; //对注册表操作 using System.Collections; //使用Arraylist using System.Security.Cryptography;//加密解密 using System.IO; //文件操作 using System.Runtime.InteropServices;//调用DLL DllImport using System.Management; //获取硬件信息 using System.Net; //获取IP地址是用到 using System.Drawing; //image using System.Net.NetworkInformation; //ping 用到 using System.Text.RegularExpressions; //正则 using System.Data; using System.Data.SqlClient; using Microsoft.VisualBasic; //简体转繁体时用到 using System.Web; //html UrlEncode #region 注册表操作 public class GF_RegReadWrite { /// <summary> /// 读取路径为keypath,键名为keyname的注册表键值,缺省返回def /// </summary> /// <param name="rootkey"></param> /// <param name="keypath">路径</param> /// <param name="keyname">键名</param> /// <param name="rtn">默认为null</param> /// <returns></returns> static public bool GetRegVal(RegistryKey rootkey, string keypath, string keyname, out string rtn) { rtn = ""; try { RegistryKey key = rootkey.OpenSubKey(keypath); rtn = key.GetValue(keyname).ToString(); key.Close(); return true; } catch { return false; } } /// <summary> /// 设置路径为keypath,键名为keyname的注册表键值为keyval /// </summary> /// <param name="rootkey"></param> /// <param name="keypath"></param> /// <param name="keyname"></param> /// <param name="keyval"></param> /// <returns></returns> static public bool SetRegVal(RegistryKey rootkey, string keypath, string keyname, string keyval) { try { RegistryKey key = rootkey.OpenSubKey(keypath, true); if (key == null) key = rootkey.CreateSubKey(keypath); key.SetValue(keyname, (object)keyval); key.Close(); return true; } catch { return false; } } /// 创建路径为keypath的键 private RegistryKey CreateRegKey(RegistryKey rootkey, string keypath) { try { return rootkey.CreateSubKey(keypath); } catch { return null; } } /// 删除路径为keypath的子项 private bool DelRegSubKey(RegistryKey rootkey, string keypath) { try { rootkey.DeleteSubKey(keypath); return true; } catch { return false; } } /// 删除路径为keypath的子项及其附属子项 private bool DelRegSubKeyTree(RegistryKey rootkey, string keypath) { try { rootkey.DeleteSubKeyTree(keypath); return true; } catch { return false; } } /// 删除路径为keypath下键名为keyname的键值 private bool DelRegKeyVal(RegistryKey rootkey, string keypath, string keyname) { try { RegistryKey key = rootkey.OpenSubKey(keypath, true); key.DeleteValue(keyname); return true; } catch { return false; } } } #endregion #region 类型转换 public class GF_Convert { /// <summary> /// 字符串 转换 char数组 /// </summary> /// <param name="in_str"></param> /// <param name="in_len"></param> /// <returns></returns> public static char[] string2chararray(string in_str, int in_len) { char[] ch = new char[in_len]; in_str.ToCharArray().CopyTo(ch, 0); return ch; } /// <summary> /// char数组 转换 字符串 /// </summary> /// <param name="in_str"></param> /// <returns></returns> public static string chararray2string(char[] in_str) { string out_str; out_str = new string(in_str); int i = out_str.IndexOf('\0', 0); if (i == -1) i = 16; return out_str.Substring(0, i); } /// <summary> /// byte数组 转换 字符串 /// </summary> /// <param name="in_str"></param> /// <returns></returns> public static string bytearray2string(byte[] in_str) { string out_str; out_str = System.Text.Encoding.Default.GetString(in_str); return out_str.Substring(0, out_str.IndexOf('\0', 0)); } /// <summary> /// 字符串 转换 byte数组 注意转换出来会使原来的bytearray长度变短 /// </summary> /// <param name="in_str"></param> /// <returns></returns> public static byte[] string2bytearray(string in_str) { return System.Text.Encoding.Default.GetBytes(in_str); } /// <summary> /// 字符串 转换 byte数组 长度为传如的长度 /// </summary> /// <param name="in_str">传入字符串</param> /// <param name="iLen">目标字节数组长度</param> /// <returns></returns> public static byte[] string2bytearray(string in_str, int iLen) { byte[] bytes = new byte[iLen]; byte[] bsources = System.Text.Encoding.Default.GetBytes(in_str); Array.Copy(bsources, bytes, bsources.Length); return bytes; } /// <summary> /// 将字符串编码为Base64字符串 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string Base64Encode(string str) { byte[] barray; barray = Encoding.Default.GetBytes(str); return Convert.ToBase64String(barray); } /// <summary> /// 将Base64字符串解码为普通字符串 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string Base64Decode(string str) { byte[] barray; try { barray = Convert.FromBase64String(str); return Encoding.Default.GetString(barray); } catch { return str; } } /// <summary> /// 图片 转换 byte数组 /// </summary> /// <param name="pic"></param> /// <param name="fmt"></param> /// <returns></returns> public static byte[] image_Image2Byte(Image pic, System.Drawing.Imaging.ImageFormat fmt) { MemoryStream mem = new MemoryStream(); pic.Save(mem, fmt); mem.Flush(); return mem.ToArray(); } /// <summary> /// byte数组 转换 图片 /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static Image image_Byte2Image(byte[] bytes) { MemoryStream mem = new MemoryStream(bytes, true); mem.Read(bytes, 0, bytes.Length); mem.Flush(); Image aa = Image.FromStream(mem); return aa; } /// <summary> /// ip 转换 长整形 /// </summary> /// <param name="strIP"></param> /// <returns></returns> public static long IP2Long(string strIP) { long[] ip = new long[4]; string[] s = strIP.Split('.'); ip[0] = long.Parse(s[0]); ip[1] = long.Parse(s[1]); ip[2] = long.Parse(s[2]); ip[3] = long.Parse(s[3]); return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3]; } /// <summary> /// 长整形 转换 IP /// </summary> /// <param name="longIP"></param> /// <returns></returns> public static string Long2IP(long longIP) { StringBuilder sb = new StringBuilder(""); sb.Append(longIP >> 24); sb.Append("."); //将高8位置0,然后右移16为 sb.Append((longIP & 0x00FFFFFF) >> 16); sb.Append("."); sb.Append((longIP & 0x0000FFFF) >> 8); sb.Append("."); sb.Append((longIP & 0x000000FF)); return sb.ToString(); } /// <summary> /// 将8位日期型整型数据转换为日期字符串数据 /// </summary> /// <param name="date">整型日期</param> /// <param name="chnType">是否以中文年月日输出</param> /// <returns></returns> public static string FormatDate(int date, bool chnType) { string dateStr = date.ToString(); if (date <= 0 || dateStr.Length != 8) return dateStr; if (chnType) return dateStr.Substring(0, 4) + "年" + dateStr.Substring(4, 2) + "月" + dateStr.Substring(6) + "日"; return dateStr.Substring(0, 4) + "-" + dateStr.Substring(4, 2) + "-" + dateStr.Substring(6); } /// <summary> /// string型转换为bool型 /// </summary> /// <param name="strValue">要转换的字符串</param> /// <param name="defValue">缺省值</param> /// <returns>转换后的bool类型结果</returns> public static bool StrToBool(object expression, bool defValue) { if (expression != null) return StrToBool(expression, defValue); return defValue; } /// <summary> /// string型转换为bool型 /// </summary> /// <param name="strValue">要转换的字符串</param> /// <param name="defValue">缺省值</param> /// <returns>转换后的bool类型结果</returns> public static bool StrToBool(string expression, bool defValue) { if (expression != null) { if (string.Compare(expression, "true", true) == 0) return true; else if (string.Compare(expression, "false", true) == 0) return false; } return defValue; } /// <summary> /// 将对象转换为Int32类型 /// </summary> /// <param name="strValue">要转换的字符串</param> /// <param name="defValue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static int ObjectToInt(object expression) { return ObjectToInt(expression, 0); } /// <summary> /// 将对象转换为Int32类型 /// </summary> /// <param name="strValue">要转换的字符串</param> /// <param name="defValue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static int ObjectToInt(object expression, int defValue) { if (expression != null) return StrToInt(expression.ToString(), defValue); return defValue; } /// <summary> /// 将对象转换为Int32类型,转换失败返回0 /// </summary> /// <param name="str">要转换的字符串</param> /// <returns>转换后的int类型结果</returns> public static int StrToInt(string str) { return StrToInt(str, 0); } /// <summary> /// 将对象转换为Int32类型 /// </summary> /// <param name="str">要转换的字符串</param> /// <param name="defValue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static int StrToInt(string str, int defValue) { if (string.IsNullOrEmpty(str) || str.Trim().Length >= 11 || !Regex.IsMatch(str.Trim(), @"^([-]|[0-9])[0-9]*(\.\w*)?$")) return defValue; int rv; if (Int32.TryParse(str, out rv)) return rv; return Convert.ToInt32(StrToFloat(str, defValue)); } /// <summary> /// string型转换为float型 /// </summary> /// <param name="strValue">要转换的字符串</param> /// <param name="defValue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static float StrToFloat(object strValue, float defValue) { if ((strValue == null)) return defValue; return StrToFloat(strValue.ToString(), defValue); } /// <summary> /// string型转换为float型 /// </summary> /// <param name="strValue">要转换的字符串</param> /// <param name="defValue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static float ObjectToFloat(object strValue, float defValue) { if ((strValue == null)) return defValue; return StrToFloat(strValue.ToString(), defValue); } /// <summary> /// string型转换为float型 /// </summary> /// <param name="strValue">要转换的字符串</param> /// <param name="defValue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static float ObjectToFloat(object strValue) { return ObjectToFloat(strValue.ToString(), 0); } /// <summary> /// string型转换为float型 /// </summary> /// <param name="strValue">要转换的字符串</param> /// <returns>转换后的int类型结果</returns> public static float StrToFloat(string strValue) { if ((strValue == null)) return 0; return StrToFloat(strValue.ToString(), 0); } /// <summary> /// string型转换为float型 /// </summary> /// <param name="strValue">要转换的字符串</param> /// <param name="defValue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static float StrToFloat(string strValue, float defValue) { if ((strValue == null) || (strValue.Length > 10)) return defValue; float intValue = defValue; if (strValue != null) { bool IsFloat = Regex.IsMatch(strValue, @"^([-]|[0-9])[0-9]*(\.\w*)?$"); if (IsFloat) float.TryParse(strValue, out intValue); } return intValue; } /// <summary> /// 将对象转换为日期时间类型 /// </summary> /// <param name="str">要转换的字符串</param> /// <param name="defValue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static DateTime StrToDateTime(string str, DateTime defValue) { if (!string.IsNullOrEmpty(str)) { DateTime dateTime; if (DateTime.TryParse(str, out dateTime)) return dateTime; } return defValue; } /// <summary> /// 将对象转换为日期时间类型 /// </summary> /// <param name="str">要转换的字符串</param> /// <returns>转换后的int类型结果</returns> public static DateTime StrToDateTime(string str) { return StrToDateTime(str, DateTime.Now); } /// <summary> /// 将对象转换为日期时间类型 /// </summary> /// <param name="obj">要转换的对象</param> /// <returns>转换后的int类型结果</returns> public static DateTime ObjectToDateTime(object obj) { return StrToDateTime(obj.ToString()); } /// <summary> /// 将对象转换为日期时间类型 /// </summary> /// <param name="obj">要转换的对象</param> /// <param name="defValue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static DateTime ObjectToDateTime(object obj, DateTime defValue) { return StrToDateTime(obj.ToString(), defValue); } /// <summary> /// 替换回车换行符为html换行符 /// </summary> public static string StrFormat(string str) { string str2; if (str == null) { str2 = ""; } else { str = str.Replace("\r\n", "<br />"); str = str.Replace("\n", "<br />"); str2 = str; } return str2; } /// <summary> /// 转换为简体中文 /// </summary> public static string ToSChinese(string str) { return Strings.StrConv(str, VbStrConv.SimplifiedChinese, 0); } /// <summary> /// 转换为繁体中文 /// </summary> public static string ToTChinese(string str) { return Strings.StrConv(str, VbStrConv.TraditionalChinese, 0); } /// <summary> /// 清除字符串数组中的重复项 /// </summary> /// <param name="strArray">字符串数组</param> /// <param name="maxElementLength">字符串数组中单个元素的最大长度</param> /// <returns></returns> public static string[] DistinctStringArray(string[] strArray, int maxElementLength) { Hashtable h = new Hashtable(); foreach (string s in strArray) { string k = s; if (maxElementLength > 0 && k.Length > maxElementLength) { k = k.Substring(0, maxElementLength); } h[k.Trim()] = s; } string[] result = new string[h.Count]; h.Keys.CopyTo(result, 0); return result; } /// <summary> /// 清除字符串数组中的重复项 /// </summary> /// <param name="strArray">字符串数组</param> /// <returns></returns> public static string[] DistinctStringArray(string[] strArray) { return DistinctStringArray(strArray, 0); } } #endregion #region 加密解密 public class GF_Encrypt { /// <summary> /// DES加密 /// </summary> /// <param name="pToEncrypt">加密字符串</param> /// <param name="sKey">密钥</param> /// <returns></returns> public static string string_Encrypt(string pToEncrypt, string sKey) { if (pToEncrypt == "") return ""; if (sKey.Length < 8) sKey = sKey + "xuE29xWp"; if (sKey.Length > 8) sKey = sKey.Substring(0, 8); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); //把字符串放到byte数组中 //原来使用的UTF8编码,我改成Unicode编码了,不行 byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt); //建立加密对象的密钥和偏移量 //原文使用ASCIIEncoding.ASCII方法的GetBytes方法 //使得输入密码必须输入英文文本 des.Key = ASCIIEncoding.Default.GetBytes(sKey); des.IV = ASCIIEncoding.Default.GetBytes(sKey); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); //Write the byte array into the crypto stream //(It will end up in the memory stream) cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); //Get the data back from the memory stream, and into a string StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { //Format as hex ret.AppendFormat("{0:X2}", b); } ret.ToString(); return ret.ToString(); } /// <summary> /// DES解密 /// </summary> /// <param name="pToDecrypt">解密字符串</param> /// <param name="sKey">解密密钥</param> /// <param name="outstr">返回值</param> /// <returns></returns> public static bool string_Decrypt(string pToDecrypt, string sKey, out string outstr) { if (pToDecrypt == "") { outstr = ""; return true; }; if (sKey.Length < 8) sKey = sKey + "xuE29xWp"; if (sKey.Length > 8) sKey = sKey.Substring(0, 8); try { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); //Put the input string into the byte array byte[] inputByteArray = new byte[pToDecrypt.Length / 2]; for (int x = 0; x < pToDecrypt.Length / 2; x++) { int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16)); inputByteArray[x] = (byte)i; } //建立加密对象的密钥和偏移量,此值重要,不能修改 des.Key = ASCIIEncoding.Default.GetBytes(sKey); des.IV = ASCIIEncoding.Default.GetBytes(sKey); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); //Flush the data through the crypto stream into the memory stream cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); //Get the decrypted data back from the memory stream //建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象 StringBuilder ret = new StringBuilder(); outstr = System.Text.Encoding.Default.GetString(ms.ToArray()); return true; } catch { outstr = ""; return false; } } /// <summary> /// 加密 /// </summary> public class AES { //默认密钥向量 private static byte[] Keys = { 0x41, 0x72, 0x65, 0x79, 0x6F, 0x75, 0x6D, 0x79, 0x53, 0x6E, 0x6F, 0x77, 0x6D, 0x61, 0x6E, 0x3F }; public static string Encode(string encryptString, string encryptKey) { encryptKey = GF_GET.GetSubString(encryptKey, 32, ""); encryptKey = encryptKey.PadRight(32, ' '); RijndaelManaged rijndaelProvider = new RijndaelManaged(); rijndaelProvider.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 32)); rijndaelProvider.IV = Keys; ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor(); byte[] inputData = Encoding.UTF8.GetBytes(encryptString); byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length); return Convert.ToBase64String(encryptedData); } public static string Decode(string decryptString, string decryptKey) { try { decryptKey = GF_GET.GetSubString(decryptKey, 32, ""); decryptKey = decryptKey.PadRight(32, ' '); RijndaelManaged rijndaelProvider = new RijndaelManaged(); rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey); rijndaelProvider.IV = Keys; ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor(); byte[] inputData = Convert.FromBase64String(decryptString); byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length); return Encoding.UTF8.GetString(decryptedData); } catch { return ""; } } } /// <summary> /// 加密 /// </summary> public class DES { //默认密钥向量 private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; /// <summary> /// DES加密字符串 /// </summary> /// <param name="encryptString">待加密的字符串</param> /// <param name="encryptKey">加密密钥,要求为8位</param> /// <returns>加密成功返回加密后的字符串,失败返回源串</returns> public static string Encode(string encryptString, string encryptKey) { encryptKey = GF_GET.GetSubString(encryptKey, 8, ""); encryptKey = encryptKey.PadRight(8, ' '); byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8)); byte[] rgbIV = Keys; byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString); DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Convert.ToBase64String(mStream.ToArray()); } /// <summary> /// DES解密字符串 /// </summary> /// <param name="decryptString">待解密的字符串</param> /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param> /// <returns>解密成功返回解密后的字符串,失败返源串</returns> public static string Decode(string decryptString, string decryptKey) { try { decryptKey = GF_GET.GetSubString(decryptKey, 8, ""); decryptKey = decryptKey.PadRight(8, ' '); byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey); byte[] rgbIV = Keys; byte[] inputByteArray = Convert.FromBase64String(decryptString); DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Encoding.UTF8.GetString(mStream.ToArray()); } catch { return ""; } } } /// <summary> /// MD5函数 /// </summary> /// <param name="str">原始字符串</param> /// <returns>MD5结果</returns> public static string MD5(string str) { byte[] b = Encoding.UTF8.GetBytes(str); b = new MD5CryptoServiceProvider().ComputeHash(b); string ret = ""; for (int i = 0; i < b.Length; i++) ret += b[i].ToString("x").PadLeft(2, '0'); return ret; } /// <summary> /// SHA256函数 /// </summary> /// /// <param name="str">原始字符串</param> /// <returns>SHA256结果</returns> public static string SHA256(string str) { byte[] SHA256Data = Encoding.UTF8.GetBytes(str); SHA256Managed Sha256 = new SHA256Managed(); byte[] Result = Sha256.ComputeHash(SHA256Data); return Convert.ToBase64String(Result); //返回长度为44字节的字符串 } } #endregion #region 读取ini文件 //读写INI public class GF_INI { [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); [DllImport("kernel32.dll")] public static extern int Beep(int dwFreq, int dwDuration); //读ini public static void iniFile_SetVal(string in_filename, string Section, string Key, string Value) { WritePrivateProfileString(Section, Key, Value, in_filename); } //写INI public static string iniFile_GetVal(string in_filename, string Section, string Key) { StringBuilder temp = new StringBuilder(255); int i = GetPrivateProfileString(Section, Key, "", temp, 255, in_filename); if (i == 0) return ""; else return temp.ToString(); } } #endregion #region 硬件信息 //硬件信息 public class GF_Hardware { /// <summary> /// cpu序列号 /// </summary> /// <returns></returns> public static string getID_CpuId() { string cpuInfo = "";//cpu序列号 ManagementClass cimobject = new ManagementClass("Win32_Processor"); ManagementObjectCollection moc = cimobject.GetInstances(); foreach (ManagementObject mo in moc) { cpuInfo = mo.Properties["ProcessorId"].Value.ToString(); } return cpuInfo; } /// <summary> /// 硬盘ID号 /// </summary> /// <returns></returns> public static string getID_HardDiskId() { string HDid = ""; ManagementClass cimobject = new ManagementClass("Win32_DiskDrive"); ManagementObjectCollection moc = cimobject.GetInstances(); foreach (ManagementObject mo in moc) { HDid = (string)mo.Properties["Model"].Value; } return HDid; } /// <summary> /// 获取网卡MacAddress /// </summary> /// <returns></returns> public static string getID_NetCardId() { string NCid = ""; ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if ((bool)mo["IPEnabled"] == true) NCid = mo["MacAddress"].ToString(); mo.Dispose(); } return NCid; } } #endregion #region 网络部分 //网络部分 public class GF_Network { /// <summary> /// 获取IP地址 返回第一个 /// </summary> /// <returns></returns> public static string getIP_This() { IPHostEntry hostInfo = Dns.GetHostEntry(Dns.GetHostName()); IPAddress[] address = hostInfo.AddressList; if (address.Length == 0) return ""; else return address[0].ToString(); } /// <summary> /// ping IP地址 timeout 局域网用200,广域网用2000 /// </summary> /// <param name="ip">IP地址</param> /// <param name="timeout">超时 毫秒</param> /// <returns></returns> public static bool ping(string ip, int timeout) { IPAddress ipadd; if (!IPAddress.TryParse(ip, out ipadd)) { return false; } Ping pingSender = new Ping(); PingReply reply = pingSender.Send(ip, timeout, new Byte[] { Convert.ToByte(1) }); if (reply.Status == IPStatus.Success) return true; else return false; } /// <summary> /// 判读是否是IP地址 /// </summary> /// <param name="in_str"></param> /// <returns></returns> public static bool IsIPStr(string in_str) { if (in_str.Replace(".", "").Length != in_str.Length - 3) return false; try { IPAddress ip = IPAddress.Parse(in_str); return true; } catch { return false; } } } #endregion #region 文件操作 //文件操作 public class GF_File { /// <summary> /// 写日志文件 /// </summary> /// <param name="sPath"> 年月 例 2011-04</param> /// <param name="sFileName">月日 例 04-22</param> /// <param name="content">时间+ 内容</param> /// <returns></returns> public static bool WriteLog(string sPath, string sFileName, string content) { try { StreamWriter sr; if (!Directory.Exists(sPath)) { Directory.CreateDirectory(sPath); } string v_filename = sPath + "\" + sFileName; if (!File.Exists(v_filename)) //如果文件存在,则创建File.AppendText对象 { sr = File.CreateText(v_filename); sr.Close(); } using (FileStream fs = new FileStream(v_filename, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.Write)) { using (sr = new StreamWriter(fs)) { sr.WriteLine(DateTime.Now.ToString("hh:mm:ss") + " " + content); sr.Close(); } fs.Close(); } return true; } catch { return false; } } /// <summary> /// 读取文本文件内容,每行存入arrayList 并返回arrayList对象 /// </summary> /// <param name="sFileName"></param> /// <returns>arrayList</returns> public static ArrayList ReadFileRow(string sFileName) { string sLine = ""; ArrayList alTxt = null; try { using (StreamReader sr = new StreamReader(sFileName)) { alTxt = new ArrayList(); while (!sr.EndOfStream) { sLine = sr.ReadLine(); if (sLine != "") { alTxt.Add(sLine.Trim()); } } sr.Close(); } } catch { } return alTxt; } /// <summary> /// 备份文件 /// </summary> /// <param name="sourceFileName">源文件名</param> /// <param name="destFileName">目标文件名</param> /// <param name="overwrite">当目标文件存在时是否覆盖</param> /// <returns>操作是否成功</returns> public static bool BackupFile(string sourceFileName, string destFileName, bool overwrite) { if (!System.IO.File.Exists(sourceFileName)) throw new FileNotFoundException(sourceFileName + "文件不存在!"); if (!overwrite && System.IO.File.Exists(destFileName)) return false; try { System.IO.File.Copy(sourceFileName, destFileName, true); return true; } catch (Exception e) { throw e; } } /// <summary> /// 备份文件,当目标文件存在时覆盖 /// </summary> /// <param name="sourceFileName">源文件名</param> /// <param name="destFileName">目标文件名</param> /// <returns>操作是否成功</returns> public static bool BackupFile(string sourceFileName, string destFileName) { return BackupFile(sourceFileName, destFileName, true); } /// <summary> /// 恢复文件 /// </summary> /// <param name="backupFileName">备份文件名</param> /// <param name="targetFileName">要恢复的文件名</param> /// <param name="backupTargetFileName">要恢复文件再次备份的名称,如果为null,则不再备份恢复文件</param> /// <returns>操作是否成功</returns> public static bool RestoreFile(string backupFileName, string targetFileName, string backupTargetFileName) { try { if (!System.IO.File.Exists(backupFileName)) throw new FileNotFoundException(backupFileName + "文件不存在!"); if (backupTargetFileName != null) { if (!System.IO.File.Exists(targetFileName)) throw new FileNotFoundException(targetFileName + "文件不存在!无法备份此文件!"); else System.IO.File.Copy(targetFileName, backupTargetFileName, true); } System.IO.File.Delete(targetFileName); System.IO.File.Copy(backupFileName, targetFileName); } catch (Exception e) { throw e; } return true; } public static bool RestoreFile(string backupFileName, string targetFileName) { return RestoreFile(backupFileName, targetFileName, null); } } #endregion #region 屏幕操作 //获取部分 public class GF_GET { /// <summary> /// 根据坐标点获取屏幕图像 /// </summary> /// <param name="x1">左上角横坐标</param> /// <param name="y1">左上角纵坐标</param> /// <param name="x2">右下角横坐标</param> /// <param name="y2">右下角纵坐标</param> /// <returns></returns> public static Image GetScreen(int x1, int y1, int x2, int y2) { int w = (x2 - x1); int h = (y2 - y1); Image myImage = new Bitmap(w, h); Graphics g = Graphics.FromImage(myImage); g.CopyFromScreen(new Point(x1, y1), new Point(0, 0), new Size(w, h)); IntPtr dc1 = g.GetHdc(); g.ReleaseHdc(dc1); return myImage; } /// <summary> /// 获取指定文件的扩展名 例: .txt /// </summary> /// <param name="fileName">指定文件名</param> /// <returns>扩展名</returns> public static string GetFileExtName(string fileName) { if (GF_IsOk.IsStrNullOrEmpty(fileName) || fileName.IndexOf('.') <= 0) return ""; fileName = fileName.ToLower().Trim(); return fileName.Substring(fileName.LastIndexOf('.'), fileName.Length - fileName.LastIndexOf('.')); } public static string GetSubString(string p_SrcString, int p_Length, string p_TailString) { return GetSubString(p_SrcString, 0, p_Length, p_TailString); } public static string GetUnicodeSubString(string str, int len, string p_TailString) { string result = string.Empty;// 最终返回的结果 int byteLen = System.Text.Encoding.Default.GetByteCount(str);// 单字节字符长度 int charLen = str.Length;// 把字符平等对待时的字符串长度 int byteCount = 0;// 记录读取进度 int pos = 0;// 记录截取位置 if (byteLen > len) { for (int i = 0; i < charLen; i++) { if (Convert.ToInt32(str.ToCharArray()[i]) > 255)// 按中文字符计算加2 byteCount += 2; else// 按英文字符计算加1 byteCount += 1; if (byteCount > len)// 超出时只记下上一个有效位置 { pos = i; break; } else if (byteCount == len)// 记下当前位置 { pos = i + 1; break; } } if (pos >= 0) result = str.Substring(0, pos) + p_TailString; } else result = str; return result; } /// <summary> /// 取指定长度的字符串 /// </summary> /// <param name="p_SrcString">要检查的字符串</param> /// <param name="p_StartIndex">起始位置</param> /// <param name="p_Length">指定长度</param> /// <param name="p_TailString">用于替换的字符串</param> /// <returns>截取后的字符串</returns> public static string GetSubString(string p_SrcString, int p_StartIndex, int p_Length, string p_TailString) { string myResult = p_SrcString; Byte[] bComments = Encoding.UTF8.GetBytes(p_SrcString); foreach (char c in Encoding.UTF8.GetChars(bComments)) { //当是日文或韩文时(注:中文的范围:\u4e00 - \u9fa5, 日文在\u0800 - \u4e00, 韩文为\xAC00-\xD7A3) if ((c > '\u0800' && c < '\u4e00') || (c > '\xAC00' && c < '\xD7A3')) { //if (System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\u0800-\u4e00]+") || System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\xAC00-\xD7A3]+")) //当截取的起始位置超出字段串长度时 if (p_StartIndex >= p_SrcString.Length) return ""; else return p_SrcString.Substring(p_StartIndex, ((p_Length + p_StartIndex) > p_SrcString.Length) ? (p_SrcString.Length - p_StartIndex) : p_Length); } } if (p_Length >= 0) { byte[] bsSrcString = Encoding.Default.GetBytes(p_SrcString); //当字符串长度大于起始位置 if (bsSrcString.Length > p_StartIndex) { int p_EndIndex = bsSrcString.Length; //当要截取的长度在字符串的有效长度范围内 if (bsSrcString.Length > (p_StartIndex + p_Length)) { p_EndIndex = p_Length + p_StartIndex; } else { //当不在有效范围内时,只取到字符串的结尾 p_Length = bsSrcString.Length - p_StartIndex; p_TailString = ""; } int nRealLength = p_Length; int[] anResultFlag = new int[p_Length]; byte[] bsResult = null; int nFlag = 0; for (int i = p_StartIndex; i < p_EndIndex; i++) { if (bsSrcString[i] > 127) { nFlag++; if (nFlag == 3) nFlag = 1; } else nFlag = 0; anResultFlag[i] = nFlag; } if ((bsSrcString[p_EndIndex - 1] > 127) && (anResultFlag[p_Length - 1] == 1)) nRealLength = p_Length + 1; bsResult = new byte[nRealLength]; Array.Copy(bsSrcString, p_StartIndex, bsResult, 0, nRealLength); myResult = Encoding.Default.GetString(bsResult); myResult = myResult + p_TailString; } } return myResult; } /// <summary> /// 获取Email HostName 例 liyangfd@gmail.com 获取出来时@gmail.com /// </summary> /// <param name="strEmail"></param> /// <returns></returns> public static string GetEmailHostName(string strEmail) { if (strEmail.IndexOf("@") < 0) { return ""; } return strEmail.Substring(strEmail.LastIndexOf("@")).ToLower(); } /// <summary> /// 返回URL中结尾的文件名 /// </summary> public static string GetFilename(string url) { if (url == null) { return ""; } string[] strs1 = url.Split(new char[] { '/' }); return strs1[strs1.Length - 1].Split(new char[] { '?' })[0]; } /// <summary> /// 根据阿拉伯数字返回月份的名称(可更改为某种语言) /// </summary> public static string[] Monthes { get { return new string[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; } } } #endregion #region 判断操作 //判断部分 public class GF_IsOk { /// <summary> /// 判读是否是IP地址 /// </summary> /// <param name="in_str"></param> /// <returns></returns> public static bool IsIPStr(string in_str) { IPAddress ip; return IPAddress.TryParse(in_str, out ip); } /// <summary> /// 判断是否是数字 /// </summary> /// <param name="strNumber"></param> /// <returns></returns> public static bool IsNumber(string strNumber) { Regex objNotNumberPattern = new Regex("[^0-9.-]"); Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*"); Regex objTwoMinusPattern = new Regex("[0-9]*[-][0-9]*[-][0-9]*"); String strValidRealPattern = "^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$"; String strValidIntegerPattern = "^([-]|[0-9])[0-9]*$"; Regex objNumberPattern = new Regex("(" + strValidRealPattern + ")|(" + strValidIntegerPattern + ")"); return !objNotNumberPattern.IsMatch(strNumber) && !objTwoDotPattern.IsMatch(strNumber) && !objTwoMinusPattern.IsMatch(strNumber) && objNumberPattern.IsMatch(strNumber); } /// <summary> /// 判断是否是日期字符串 /// </summary> /// <param name="in_str"></param> /// <returns></returns> public static bool IsDateStr_yyyymmdd(string in_str) { if (in_str == "") return true; if (in_str.Length != 8) return false; return IsDateStr(in_str); } /// <summary> /// 判断是否是日期字符串 /// </summary> /// <param name="in_str"></param> /// <returns></returns> public static bool IsDateStr(string in_str) { if (in_str == "") return true; if (in_str.Length == 8) in_str = in_str.Substring(0, 4) + "-" + in_str.Substring(4, 2) + "-" + in_str.Substring(6, 2); DateTime dtDate; bool bValid = true; try { dtDate = DateTime.Parse(in_str); } catch (FormatException) { // 如果解析方法失败则表示不是日期性数据 bValid = false; } return bValid; } /// <summary> /// 判断字符串中是否包含汉字,有返回true 否则为false /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsExistHanZi(string str) { Regex reg = new Regex(@"[\u4e00-\u9fa5]");//正则表达式 if (reg.IsMatch(str)) { return true; } else { return false; } } /// <summary> /// 字段串是否为Null或为""(空) /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsStrNullOrEmpty(string str) { if (str == null || str.Trim() == string.Empty) return true; return false; } /// <summary> /// 返回文件是否存在 /// </summary> /// <param name="filename">文件名</param> /// <returns>是否存在</returns> public static bool IsFileExists(string filename) { return System.IO.File.Exists(filename); } /// <summary> /// 检测是否符合email格式 /// </summary> /// <param name="strEmail">要判断的email字符串</param> /// <returns>判断结果</returns> public static bool IsValidEmail(string strEmail) { return Regex.IsMatch(strEmail, @"^[\w\.]+([-]\w+)*@[A-Za-z0-9-_]+[\.][A-Za-z0-9-_]"); } public static bool IsValidDoEmail(string strEmail) { return Regex.IsMatch(strEmail, @"^@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); } /// <summary> /// 检测是否是正确的Url /// </summary> /// <param name="strUrl">要验证的Url</param> /// <returns>判断结果</returns> public static bool IsURL(string strUrl) { return Regex.IsMatch(strUrl, @"^(http|https)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{1,10}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$"); } /// <summary> /// 判断是否为base64字符串 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsBase64String(string str) { //A-Z, a-z, 0-9, +, /, = return Regex.IsMatch(str, @"[A-Za-z0-9\+\/\=]"); } /// <summary> /// 检测是否有Sql危险字符 /// </summary> /// <param name="str">要判断字符串</param> /// <returns>判断结果</returns> public static bool IsSafeSqlString(string str) { return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']"); } } #endregion #region 数据库操作 //数据库 public class GF_DA { /// <summary> /// 执行SQL语句 sConnStr 连接字符串,sql执行的sql命令 返回第一行第一列 /// </summary> /// <param name="sConnStr"></param> /// <param name="sql"></param> /// <returns></returns> public static object ExecSQL(string sConnStr, string sql) { using (SqlConnection conn = new SqlConnection(sConnStr)) { using (SqlCommand cmd = new SqlCommand()) { try { conn.Open(); cmd.Connection = conn; cmd.CommandText = sql; return cmd.ExecuteScalar(); } catch { return null; } } } } /// <summary> /// 执行SQL数组 /// </summary> /// <param name="sConnStr"></param> /// <param name="alSql"></param> /// <param name="iLen"></param> public static void ExecSQL(string sConnStr, ArrayList alSql, int iLen) { using (SqlConnection conn = new SqlConnection(sConnStr)) { using (SqlCommand cmd = new SqlCommand()) { try { conn.Open(); cmd.Connection = conn; for (int i = 0; i < alSql.Count; i++) { cmd.CommandText = alSql[i].ToString(); cmd.ExecuteNonQuery(); } } catch { } } } } /// <summary> /// 填充数据 返回DataTable /// </summary> /// <param name="sConnStr"></param> /// <param name="sql"></param> /// <param name="sTableName"></param> /// <returns></returns> public static DataTable DataFill(string sConnStr, string sql, string sTableName) { using (SqlConnection conn = new SqlConnection(sConnStr)) { using (SqlCommand cmd = new SqlCommand()) { DataSet ds = new DataSet(); try { conn.Open(); cmd.Connection = conn; cmd.CommandText = sql; SqlDataAdapter ap = new SqlDataAdapter(cmd); ap.Fill(ds, sTableName); return ds.Tables[0]; } catch { return null; } } } } } #endregion #region 各种进制转换 public sealed class DataConvert { #region Helperfunctions /// <summary> /// 十进制转换为二进制 /// </summary> /// <param name="x"></param> /// <returns></returns> public static string DecToBin(string x) { string z = null; int X = Convert.ToInt32(x); int i = 0; long a, b = 0; while (X > 0) { a = X % 2; X = X / 2; b = b + a * Pow(10, i); i++; } z = Convert.ToString(b); return z; } /// <summary> /// 16进制转ASCII码 /// </summary> /// <param name="hexString"></param> /// <returns></returns> public static string HexToAscii(string hexString) { StringBuilder sb = new StringBuilder(); for (int i = 0; i <= hexString.Length - 2; i += 2) { sb.Append( Convert.ToString( Convert.ToChar(Int32.Parse(hexString.Substring(i, 2), System.Globalization.NumberStyles.HexNumber)))); } return sb.ToString(); } /// <summary> /// 十进制转换为八进制 /// </summary> /// <param name="x"></param> /// <returns></returns> public static string DecToOtc(string x) { string z = null; int X = Convert.ToInt32(x); int i = 0; long a, b = 0; while (X > 0) { a = X % 8; X = X / 8; b = b + a * Pow(10, i); i++; } z = Convert.ToString(b); return z; } /// <summary> /// 十进制转换为十六进制 /// </summary> /// <param name="x"></param> /// <returns></returns> public static string DecToHex(string x) { if (string.IsNullOrEmpty(x)) { return "0"; } string z = null; int X = Convert.ToInt32(x); Stack a = new Stack(); int i = 0; while (X > 0) { a.Push(Convert.ToString(X % 16)); X = X / 16; i++; } while (a.Count != 0) z += ToHex(Convert.ToString(a.Pop())); if (string.IsNullOrEmpty(z)) { z = "0"; } return z; } /// <summary> /// 二进制转换为十进制 /// </summary> /// <param name="x"></param> /// <returns></returns> public static string BinToDec(string x) { string z = null; int X = Convert.ToInt32(x); int i = 0; long a, b = 0; while (X > 0) { a = X % 10; X = X / 10; b = b + a * Pow(2, i); i++; } z = Convert.ToString(b); return z; } /// <summary> /// 二进制转换为十进制,定长转换 /// </summary> /// <param name="x"></param> /// <param name="iLength"></param> /// <returns></returns> public static string BinToDec(string x, short iLength) { StringBuilder sb = new StringBuilder(); int iCount = 0; iCount = x.Length / iLength; if (x.Length % iLength > 0) { iCount += 1; } int X = 0; for (int i = 0; i < iCount; i++) { if ((i + 1) * iLength > x.Length) { X = Convert.ToInt32(x.Substring(i * iLength, (x.Length - iLength))); } else { X = Convert.ToInt32(x.Substring(i * iLength, iLength)); } int j = 0; long a, b = 0; while (X > 0) { a = X % 10; X = X / 10; b = b + a * Pow(2, j); j++; } sb.AppendFormat("{0:D2}", b); } return sb.ToString(); } /// <summary> /// 二进制转换为十六进制,定长转换 /// </summary> /// <param name="x"></param> /// <param name="iLength"></param> /// <returns></returns> public static string BinToHex(string x, short iLength) { StringBuilder sb = new StringBuilder(); int iCount = 0; iCount = x.Length / iLength; if (x.Length % iLength > 0) { iCount += 1; } int X = 0; for (int i = 0; i < iCount; i++) { if ((i + 1) * iLength > x.Length) { X = Convert.ToInt32(x.Substring(i * iLength, (x.Length - iLength))); } else { X = Convert.ToInt32(x.Substring(i * iLength, iLength)); } int j = 0; long a, b = 0; while (X > 0) { a = X % 10; X = X / 10; b = b + a * Pow(2, j); j++; } //前补0 sb.Append(DecToHex(b.ToString())); } return sb.ToString(); } /// <summary> /// 八进制转换为十进制 /// </summary> /// <param name="x"></param> /// <returns></returns> public static string OctToDec(string x) { string z = null; int X = Convert.ToInt32(x); int i = 0; long a, b = 0; while (X > 0) { a = X % 10; X = X / 10; b = b + a * Pow(8, i); i++; } z = Convert.ToString(b); return z; } /// <summary> /// 十六进制转换为十进制 /// </summary> /// <param name="x"></param> /// <returns></returns> public static string HexToDec(string x) { if (string.IsNullOrEmpty(x)) { return "0"; } string z = null; Stack a = new Stack(); int i = 0, j = 0, l = x.Length; long Tong = 0; while (i < l) { a.Push(ToDec(Convert.ToString(x[i]))); i++; } while (a.Count != 0) { Tong = Tong + Convert.ToInt64(a.Pop()) * Pow(16, j); j++; } z = Convert.ToString(Tong); return z; } #endregion //Helperfunctions /// <summary> /// /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> private static long Pow(long x, long y) { int i = 1; long X = x; if (y == 0) return 1; while (i < y) { x = x * X; i++; } return x; } /// <summary> /// /// </summary> /// <param name="x"></param> /// <returns></returns> private static string ToDec(string x) { switch (x) { case "A": return "10"; case "B": return "11"; case "C": return "12"; case "D": return "13"; case "E": return "14"; case "F": return "15"; default: return x; } } /// <summary> /// /// </summary> /// <param name="x"></param> /// <returns></returns> private static string ToHex(string x) { switch (x) { case "10": return "A"; case "11": return "B"; case "12": return "C"; case "13": return "D"; case "14": return "E"; case "15": return "F"; default: return x; } } /// <summary> /// 将16进制BYTE数组转换成16进制字符串 /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static string ToHexString(byte[] bytes) // 0xae00cf => "AE00CF " { string hexString = string.Empty; if (bytes != null) { StringBuilder strB = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) { strB.Append(bytes[i].ToString("X2")); } hexString = strB.ToString(); } return hexString; } } #endregion
Grass Mud Horse