构建一个.net的干货类库,以便于快速的开发 - 工具类

  相信每一个开发的框架都会有一个工具类,工具类的作用有很多,通常我会将最常用的方法放在工具类里

  1. 取得用户IP
  2. 取得网站根目录的物理路径
  3. 枚举相关
  4. 非法关键字检查
  5. 绝对路径改为相对路径
  6. 获取小数位(四舍五入 ,保留小数)
  7. 生成缩略图

  当然每个开发框架的工具类都会不同,这里我只收录了这些方法,希望有更多需求的小伙伴也可以收录进工具类里

 

  

  1.取得用户IP

  做Web开发的一定会遇到获取用户IP的需求的,无论是用来记录登录时间,还是日志的记录,都要用到IP这个东西,而IP的记录一直是程序员开发的难题,因为这个IP是可以改的,也可以代理,所以在一定程度上会有偏差(IP这东西没用百分百的正确,如果有心不想让你知道的话总有办法不让你知道),所以这个方法只是说比较精确的一个获取IP的方法。

 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         }
View Code

  

  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         }
View Code

  

  3.枚举相关

  枚举在开发中的使用也是非常频繁的,毕竟枚举能够使代码更加清晰,也提高了代码的维护性,所以枚举相关的方法就显得很是实用。

  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         }
View Code

 

  4.非法关键字检查

  非法关键字检查在很多网站上也有用到,这里我收录的方法并不是最好的,但也能满足一般的需求,我觉得最好是用一个文件来保存字库去维护是最好的,有需求的小伙伴可以去搜索一下。

  

 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         }
View Code

 

  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         }
View Code

 

  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         }
View Code

 

  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         }
View Code
posted @ 2016-08-05 09:58  starmile  阅读(1157)  评论(1编辑  收藏  举报