相信每個開發的框架都會有一個工具類,工具類的做用有不少,一般我會將最經常使用的方法放在工具類裏程序員
固然每一個開發框架的工具類都會不一樣,這裏我只收錄了這些方法,但願有更多需求的小夥伴也能夠收錄進工具類裏shell
1.取得用戶IP框架
作Web開發的必定會遇到獲取用戶IP的需求的,不管是用來記錄登陸時間,仍是日誌的記錄,都要用到IP這個東西,而IP的記錄一直是程序員開發的難題,由於這個IP是能夠改的,也能夠代理,因此在必定程度上會有誤差(IP這東西沒用百分百的正確,若是有心不想讓你知道的話總有辦法不讓你知道),因此這個方法只是說比較精確的一個獲取IP的方法。ide
1 /// <summary> 2 /// 取得用戶IP 3 /// </summary> 4 /// <returns></returns> 5 public static string GetAddressIP() 6 { 7 ///獲取本地的IP地址 8 string AddressIP = string.Empty; 9 if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null) 10 { 11 AddressIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); 12 } 13 else 14 { 15 AddressIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString(); 16 } 17 return AddressIP; 18 }
2.取得網站根目錄的物理路徑工具
1 /// <summary> 2 /// 取得網站根目錄的物理路徑 3 /// </summary> 4 /// <returns></returns> 5 public static string GetRootPath() 6 { 7 string AppPath = ""; 8 HttpContext HttpCurrent = HttpContext.Current; 9 if (HttpCurrent != null) 10 { 11 AppPath = HttpCurrent.Server.MapPath("~"); 12 } 13 else 14 { 15 AppPath = AppDomain.CurrentDomain.BaseDirectory; 16 if (Regex.Match(AppPath, @"\\$", RegexOptions.Compiled).Success) 17 AppPath = AppPath.Substring(0, AppPath.Length - 1); 18 } 19 return AppPath; 20 }
3.枚舉相關網站
枚舉在開發中的使用也是很是頻繁的,畢竟枚舉可以使代碼更加清晰,也提升了代碼的維護性,因此枚舉相關的方法就顯得非常實用。ui
1 /// <summary> 2 /// 獲取枚舉列表 3 /// </summary> 4 /// <param name="enumType">枚舉的類型</param> 5 /// <returns>枚舉列表</returns> 6 public static Dictionary<int, string> GetEnumList(Type enumType) 7 { 8 Dictionary<int, string> dic = new Dictionary<int, string>(); 9 FieldInfo[] fd = enumType.GetFields(); 10 for (int index = 1; index < fd.Length; ++index) 11 { 12 FieldInfo info = fd[index]; 13 object fieldValue = Enum.Parse(enumType, fd[index].Name); 14 object[] attrs = info.GetCustomAttributes(typeof(EnumTextAttribute), false); 15 foreach (EnumTextAttribute attr in attrs) 16 { 17 int key = (int)fieldValue; 18 if (key != -100)//-100爲NULL項 19 { 20 string value = attr.Text; 21 dic.Add(key, value); 22 } 23 } 24 } 25 return dic; 26 } 27 28 /// <summary> 29 /// 獲取枚舉名稱 30 /// </summary> 31 /// <param name="enumType">枚舉的類型</param> 32 /// <param name="id">枚舉值</param> 33 /// <returns>若是枚舉值存在,返回對應的枚舉名稱,不然,返回空字符</returns> 34 public static string GetEnumTextById(Type enumType, int id) 35 { 36 string ret = ""; 37 Dictionary<int, string> dic = GetEnumList(enumType); 38 foreach (var item in dic) 39 { 40 if (item.Key == id) 41 { 42 ret = item.Value; 43 break; 44 } 45 } 46 47 return ret; 48 } 49 50 /// <summary> 51 /// 根據枚舉值獲取對應中文描述 52 /// </summary> 53 /// <param name="enumValue">枚舉值</param> 54 /// <returns>枚舉值中文描述</returns> 55 public static string GetEnumTextByEnum(object enumValue) 56 { 57 string ret = ""; 58 if ((int)enumValue != -1) 59 { 60 Dictionary<int, string> dic = GetEnumList(enumValue.GetType()); 61 foreach (var item in dic) 62 { 63 if (item.Key == (int)enumValue) 64 { 65 ret = item.Value; 66 break; 67 } 68 } 69 } 70 71 return ret; 72 } 73 74 75 76 /// <summary> 77 /// 獲取枚舉名稱 78 /// </summary> 79 /// <param name="enumType">枚舉的類型</param> 80 /// <param name="index">枚舉值的位置編號</param> 81 /// <returns>若是枚舉值存在,返回對應的枚舉名稱,不然,返回空字符</returns> 82 public static string GetEnumTextByIndex(Type enumType, int index) 83 { 84 string ret = ""; 85 86 Dictionary<int, string> dic = GetEnumList(enumType); 87 88 if (index < 0 || 89 index > dic.Count) 90 return ret; 91 92 int i = 0; 93 foreach (var item in dic) 94 { 95 if (i == index) 96 { 97 ret = item.Value; 98 break; 99 } 100 i++; 101 } 102 103 return ret; 104 } 105 106 /// <summary> 107 /// 獲取枚舉值 108 /// </summary> 109 /// <param name="enumType">枚舉的類型</param> 110 /// <param name="name">枚舉名稱</param> 111 /// <returns>若是枚舉名稱存在,返回對應的枚舉值,不然,返回-1</returns> 112 public static int GetEnumIdByName(Type enumType, string name) 113 { 114 int ret = -1; 115 116 if (string.IsNullOrEmpty(name)) 117 return ret; 118 119 Dictionary<int, string> dic = GetEnumList(enumType); 120 foreach (var item in dic) 121 { 122 if (item.Value.CompareTo(name) == 0) 123 { 124 ret = item.Key; 125 break; 126 } 127 } 128 129 return ret; 130 } 131 132 /// <summary> 133 /// 獲取名字對應枚舉值 134 /// </summary> 135 /// <typeparam name="T">枚舉類型</typeparam> 136 /// <param name="name">枚舉名稱</param> 137 /// <returns></returns> 138 public static T GetEnumIdByName<T>(string name) where T : new() 139 { 140 Type type = typeof(T); 141 T enumItem = new T(); 142 enumItem = (T)TypeDescriptor.GetConverter(type).ConvertFrom("-1"); 143 if (string.IsNullOrEmpty(name)) 144 return enumItem; 145 FieldInfo[] fd = typeof(T).GetFields(); 146 for (int index = 1; index < fd.Length; ++index) 147 { 148 FieldInfo info = fd[index]; 149 object fieldValue = Enum.Parse(type, fd[index].Name); 150 object[] attrs = info.GetCustomAttributes(typeof(EnumTextAttribute), false); 151 if (attrs.Length == 1) 152 { 153 EnumTextAttribute attr = (EnumTextAttribute)attrs[0]; 154 if (name.Equals(attr.Text)) 155 { 156 enumItem = (T)fieldValue; 157 break; 158 } 159 } 160 } 161 return enumItem; 162 } 163 164 165 /// <summary> 166 /// 獲取枚舉值所在的位置編號 167 /// </summary> 168 /// <param name="enumType">枚舉的類型</param> 169 /// <param name="name">枚舉名稱</param> 170 /// <returns>若是枚舉名稱存在,返回對應的枚舉值的位置編號,不然,返回-1</returns> 171 public static int GetEnumIndexByName(Type enumType, string name) 172 { 173 int ret = -1; 174 175 if (string.IsNullOrEmpty(name)) 176 return ret; 177 178 Dictionary<int, string> dic = GetEnumList(enumType); 179 int i = 0; 180 foreach (var item in dic) 181 { 182 if (item.Value.CompareTo(name) == 0) 183 { 184 ret = i; 185 break; 186 } 187 i++; 188 } 189 190 return ret; 191 }
4.非法關鍵字檢查編碼
非法關鍵字檢查在不少網站上也有用到,這裏我收錄的方法並非最好的,但也能知足通常的需求,我以爲最好是用一個文件來保存字庫去維護是最好的,有需求的小夥伴能夠去搜索一下。spa
1 /// <summary> 2 /// 非法關鍵字檢查 3 /// </summary> 4 /// <param name="Emtxt">要檢查的字符串</param> 5 /// <returns>若是字符串裏沒有非法關鍵字,返回true,不然,返回false</returns> 6 public static bool CheckWord(string Emtxt) 7 { 8 string keyword = @"";//由於論壇也有關鍵字檢查因此這裏的字庫就小夥伴們本身去找^_^ 9 Regex regex = new Regex(keyword, RegexOptions.IgnoreCase); 10 if (regex.IsMatch(Emtxt)) 11 { 12 return false; 13 } 14 return true; 15 } 16 17 /// <summary> 18 /// SQL注入關鍵字過濾 19 /// </summary> 20 private const string StrKeyWord = @"^\s*select | select |^\s*insert | insert |^\s*delete | delete |^\s*from | from |^\s*declare | declare |^\s*exec | exec | count\(|drop table|^\s*update | update |^\s*truncate | truncate |asc\(|mid\(|char\(|xp_cmdshell|^\s*master| master |exec master|netlocalgroup administrators|net user|""|^\s*or | or |^\s*and | and |^\s*null | null "; 21 22 /// <summary> 23 /// 關鍵字過濾 24 /// </summary> 25 /// <param name="_sWord"></param> 26 /// <returns></returns> 27 public static string ResplaceSql(string _sWord) 28 { 29 if (!string.IsNullOrEmpty(_sWord)) 30 { 31 Regex regex = new Regex(StrKeyWord, RegexOptions.IgnoreCase); 32 _sWord = regex.Replace(_sWord, ""); 33 _sWord = _sWord.Replace("'", "''"); 34 return _sWord; 35 } 36 else 37 { 38 return ""; 39 } 40 }
5.絕對路徑改成相對路徑代理
這個方法相對於前面的使用率並非很高,在特定的狀況下這個方法仍是頗有用的
1 /// <summary> 2 /// 絕對路徑改成相對路徑 3 /// </summary> 4 /// <param name="relativeTo"></param> 5 /// <returns></returns> 6 public static string RelativePath(string relativeTo) 7 { 8 string absolutePath = GetRootPath(); 9 string[] absoluteDirectories = absolutePath.Split('\\'); 10 string[] relativeDirectories = relativeTo.Split('\\'); 11 12 //得到這兩條路徑中最短的 13 int length = absoluteDirectories.Length < relativeDirectories.Length ? absoluteDirectories.Length : relativeDirectories.Length; 14 15 //用於肯定退出的循環中的地方 16 int lastCommonRoot = -1; 17 int index; 18 19 //找到共同的根目錄 20 for (index = 0; index < length; index++) 21 if (absoluteDirectories[index] == relativeDirectories[index]) 22 lastCommonRoot = index; 23 else 24 break; 25 26 //若是咱們沒有找到一個共同的前綴,而後拋出 27 if (lastCommonRoot == -1) 28 throw new ArgumentException("Paths do not have a common base"); 29 30 //創建相對路徑 31 StringBuilder relativePath = new StringBuilder(); 32 33 //加上 .. 34 for (index = lastCommonRoot + 1; index < absoluteDirectories.Length; index++) 35 if (absoluteDirectories[index].Length > 0) 36 relativePath.Append("..\\"); 37 38 //添加文件夾 39 for (index = lastCommonRoot + 1; index < relativeDirectories.Length - 1; index++) 40 relativePath.Append(relativeDirectories[index] + "\\"); 41 relativePath.Append(relativeDirectories[relativeDirectories.Length - 1]); 42 43 return relativePath.ToString(); 44 }
6.獲取小數位(四捨五入 ,保留小數)
在平常處理數字相關的時候常常會用到的方法
1 /// <summary> 2 /// 四捨五入,保留2位小數 3 /// </summary> 4 /// <param name="obj"></param> 5 /// <returns></returns> 6 public static decimal Rounding(decimal obj) 7 { 8 return Rounding(obj, 2); 9 } 10 /// <summary> 11 /// 四捨五入,保留n位小數 12 /// </summary> 13 /// <param name="obj"></param> 14 /// <param name="len">保留幾位小數</param> 15 /// <returns></returns> 16 public static decimal Rounding(decimal obj, int len) 17 { 18 return Math.Round(obj, len, MidpointRounding.AwayFromZero); 19 } 20 21 /// <summary> 22 /// 只舍不入,保留2位小數 23 /// </summary> 24 /// <param name="obj"></param> 25 /// <returns></returns> 26 public static decimal RoundingMin(decimal obj) 27 { 28 return RoundingMin(obj, 2); 29 } 30 31 /// <summary> 32 /// 只舍不入,保留n位小數 33 /// </summary> 34 /// <param name="obj"></param> 35 /// <param name="len"></param> 36 /// <returns></returns> 37 public static decimal RoundingMin(decimal obj, int len) 38 { 39 var str = "0." + "".PadLeft(len, '0') + "5"; 40 decimal dec = Convert.ToDecimal(str); 41 return Rounding(obj - dec, len); 42 } 43 44 45 /// <summary> 46 /// 只舍不入,保留2位小數 47 /// </summary> 48 /// <param name="obj"></param> 49 /// <returns></returns> 50 public static decimal RoundingMax(decimal obj) 51 { 52 return RoundingMax(obj, 2); 53 } 54 55 /// <summary> 56 /// 只舍不入,保留n位小數 57 /// </summary> 58 /// <param name="obj"></param> 59 /// <param name="len"></param> 60 /// <returns></returns> 61 public static decimal RoundingMax(decimal obj, int len) 62 { 63 var str = "0." + "".PadLeft(len, '0') + "4"; 64 decimal dec = Convert.ToDecimal(str); 65 return Rounding(obj + dec, len); 66 }
7.生成縮略圖
對於Web的開發來講,網站的空間是很是有限的,因此壓縮圖片就使得尤其重要。一張高清的圖片對於網站的帶寬來講是奢侈的,並且也佔據很是大的空間,因此上傳圖片的時候通過必定的壓縮對網站的各方面都會有更好的效果。
1 /// <summary> 2 /// 生成縮略圖 3 /// </summary> 4 /// <param name="sourceFile">原始圖片文件</param> 5 /// <param name="quality">質量壓縮比</param> 6 /// <param name="multiple">收縮倍數</param> 7 /// <param name="outputFile">輸出文件名</param> 8 /// <returns>成功返回true,失敗則返回false</returns> 9 public static bool ThumImage(string sourceFile, long quality, int multiple, string outputFile) 10 { 11 try 12 { 13 long imageQuality = quality; 14 Bitmap sourceImage = new Bitmap(sourceFile); 15 ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/jpeg"); 16 System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; 17 EncoderParameters myEncoderParameters = new EncoderParameters(1); 18 EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, imageQuality); 19 myEncoderParameters.Param[0] = myEncoderParameter; 20 float xWidth = sourceImage.Width; 21 float yWidth = sourceImage.Height; 22 Bitmap newImage = new Bitmap((int)(xWidth / multiple), (int)(yWidth / multiple)); 23 Graphics g = Graphics.FromImage(newImage); 24 25 g.DrawImage(sourceImage, 0, 0, xWidth / multiple, yWidth / multiple); 26 g.Dispose(); 27 newImage.Save(outputFile, myImageCodecInfo, myEncoderParameters); 28 sourceImage.Dispose(); 29 System.IO.File.Delete(sourceFile); 30 return true; 31 } 32 catch (Exception e) 33 { 34 return false; 35 } 36 37 } 38 39 /// <summary> 40 /// 獲取圖片編碼信息 41 /// </summary> 42 private static ImageCodecInfo GetEncoderInfo(String mimeType) 43 { 44 int j; 45 ImageCodecInfo[] encoders; 46 encoders = ImageCodecInfo.GetImageEncoders(); 47 for (j = 0; j < encoders.Length; ++j) 48 { 49 if (encoders[j].MimeType == mimeType) 50 return encoders[j]; 51 } 52 return null; 53 }