XML序列化
#region 序列化 /// <summary> /// XML序列化 /// </summary> /// <param name="obj">序列对象</param> /// <param name="filePath">XML文件路径</param> /// <returns>是否成功</returns> public static bool SerializeToXml(object obj, string filePath) { bool result = false; FileStream fs = null; try { fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); XmlSerializer serializer = new XmlSerializer(obj.GetType()); serializer.Serialize(fs, obj); result = true; } catch (Exception ex) { throw ex; } finally { if (fs != null) fs.Close(); } return result; } /// <summary> /// XML反序列化 /// </summary> /// <param name="type">目标类型(Type类型)</param> /// <param name="filePath">XML文件路径</param> /// <returns>序列对象</returns> public static object DeserializeFromXML(Type type, string filePath) { FileStream fs = null; try { fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); XmlSerializer serializer = new XmlSerializer(type); return serializer.Deserialize(fs); } catch (Exception ex) { throw ex; } finally { if (fs != null) fs.Close(); } } #endregion
判断是否是手机
public static bool CheckAgent()
{
bool flag = false;
string agent = HttpContext.Current.Request.UserAgent;
string[] keywords = { "Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser" };
//排除 Windows 桌面系统
if (!agent.Contains("Windows NT") || (agent.Contains("Windows NT") && agent.Contains("compatible; MSIE 9.0;")))
{
//排除 苹果桌面系统
if (!agent.Contains("Windows NT") && !agent.Contains("Macintosh"))
{
foreach (string item in keywords)
{
if (agent.Contains(item))
{
flag = true;
break;
}
}
}
}
return flag;
}
字符操作普通帮助类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
|
/// <summary> /// 普通帮助类
/// </summary>
public class CommonHelper
{
//星期数组
private static string [] _weekdays = { "星期日" , "星期一" , "星期二" , "星期三" , "星期四" , "星期五" , "星期六" };
//空格、回车、换行符、制表符正则表达式
private static Regex _tbbrRegex = new Regex( @"\s*|\t|\r|\n" , RegexOptions.IgnoreCase);
#region 时间操作
/// <summary>
/// 获得当前时间的""yyyy-MM-dd HH:mm:ss:fffffff""格式字符串
/// </summary>
public static string GetDateTimeMS()
{
return DateTime.Now.ToString( "yyyy-MM-dd HH:mm:ss:fffffff" );
}
/// <summary>
/// 获得当前时间的""yyyy年MM月dd日 HH:mm:ss""格式字符串
/// </summary>
public static string GetDateTimeU()
{
return string .Format( "{0:U}" , DateTime.Now);
}
/// <summary>
/// 获得当前时间的""yyyy-MM-dd HH:mm:ss""格式字符串
/// </summary>
public static string GetDateTime()
{
return DateTime.Now.ToString( "yyyy-MM-dd HH:mm:ss" );
}
/// <summary>
/// 获得当前日期
/// </summary>
public static string GetDate()
{
return DateTime.Now.ToString( "yyyy-MM-dd" );
}
/// <summary>
/// 获得中文当前日期
/// </summary>
public static string GetChineseDate()
{
return DateTime.Now.ToString( "yyyy月MM日dd" );
}
/// <summary>
/// 获得当前时间(不含日期部分)
/// </summary>
public static string GetTime()
{
return DateTime.Now.ToString( "HH:mm:ss" );
}
/// <summary>
/// 获得当前小时
/// </summary>
public static string GetHour()
{
return DateTime.Now.Hour.ToString( "00" );
}
/// <summary>
/// 获得当前天
/// </summary>
public static string GetDay()
{
return DateTime.Now.Day.ToString( "00" );
}
/// <summary>
/// 获得当前月
/// </summary>
public static string GetMonth()
{
return DateTime.Now.Month.ToString( "00" );
}
/// <summary>
/// 获得当前年
/// </summary>
public static string GetYear()
{
return DateTime.Now.Year.ToString();
}
/// <summary>
/// 获得当前星期(数字)
/// </summary>
public static string GetDayOfWeek()
{
return (( int )DateTime.Now.DayOfWeek).ToString();
}
/// <summary>
/// 获得当前星期(汉字)
/// </summary>
public static string GetWeek()
{
return _weekdays[( int )DateTime.Now.DayOfWeek];
}
#endregion
#region 数组操作
/// <summary>
/// 获得字符串在字符串数组中的位置
/// </summary>
public static int GetIndexInArray( string s, string [] array, bool ignoreCase)
{
if ( string .IsNullOrEmpty(s) || array == null || array.Length == 0)
return -1;
int index = 0;
string temp = null ;
if (ignoreCase)
s = s.ToLower();
foreach ( string item in array)
{
if (ignoreCase)
temp = item.ToLower();
else
temp = item;
if (s == temp)
return index;
else
index++;
}
return -1;
}
/// <summary>
/// 获得字符串在字符串数组中的位置
/// </summary>
public static int GetIndexInArray( string s, string [] array)
{
return GetIndexInArray(s, array, false );
}
/// <summary>
/// 判断字符串是否在字符串数组中
/// </summary>
public static bool IsInArray( string s, string [] array, bool ignoreCase)
{
return GetIndexInArray(s, array, ignoreCase) > -1;
}
/// <summary>
/// 判断字符串是否在字符串数组中
/// </summary>
public static bool IsInArray( string s, string [] array)
{
return IsInArray(s, array, false );
}
/// <summary>
/// 判断字符串是否在字符串中
/// </summary>
public static bool IsInArray( string s, string array, string splitStr, bool ignoreCase)
{
return IsInArray(s, StringHelper.SplitString(array, splitStr), ignoreCase);
}
/// <summary>
/// 判断字符串是否在字符串中
/// </summary>
public static bool IsInArray( string s, string array, string splitStr)
{
return IsInArray(s, StringHelper.SplitString(array, splitStr), false );
}
/// <summary>
/// 判断字符串是否在字符串中
/// </summary>
public static bool IsInArray( string s, string array)
{
return IsInArray(s, StringHelper.SplitString(array, "," ), false );
}
/// <summary>
/// 将对象数组拼接成字符串
/// </summary>
public static string ObjectArrayToString( object [] array, string splitStr)
{
if (array == null || array.Length == 0)
return "" ;
StringBuilder result = new StringBuilder();
for ( int i = 0; i < array.Length; i++)
result.AppendFormat( "{0}{1}" , array[i], splitStr);
return result.Remove(result.Length - splitStr.Length, splitStr.Length).ToString();
}
/// <summary>
/// 将对象数组拼接成字符串
/// </summary>
public static string ObjectArrayToString( object [] array)
{
return ObjectArrayToString(array, "," );
}
/// <summary>
/// 将字符串数组拼接成字符串
/// </summary>
public static string StringArrayToString( string [] array, string splitStr)
{
return ObjectArrayToString(array, splitStr);
}
/// <summary>
/// 将字符串数组拼接成字符串
/// </summary>
public static string StringArrayToString( string [] array)
{
return StringArrayToString(array, "," );
}
/// <summary>
/// 将整数数组拼接成字符串
/// </summary>
public static string IntArrayToString( int [] array, string splitStr)
{
if (array == null || array.Length == 0)
return "" ;
StringBuilder result = new StringBuilder();
for ( int i = 0; i < array.Length; i++)
result.AppendFormat( "{0}{1}" , array[i], splitStr);
return result.Remove(result.Length - splitStr.Length, splitStr.Length).ToString();
}
/// <summary>
/// 将整数数组拼接成字符串
/// </summary>
public static string IntArrayToString( int [] array)
{
return IntArrayToString(array, "," );
}
/// <summary>
/// 移除数组中的指定项
/// </summary>
/// <param name="array">源数组</param>
/// <param name="removeItem">要移除的项</param>
/// <param name="removeBackspace">是否移除空格</param>
/// <param name="ignoreCase">是否忽略大小写</param>
/// <returns></returns>
public static string [] RemoveArrayItem( string [] array, string removeItem, bool removeBackspace, bool ignoreCase)
{
if (array != null && array.Length > 0)
{
StringBuilder arrayStr = new StringBuilder();
if (ignoreCase)
removeItem = removeItem.ToLower();
string temp = "" ;
foreach ( string item in array)
{
if (ignoreCase)
temp = item.ToLower();
else
temp = item;
if (temp != removeItem)
arrayStr.AppendFormat( "{0}_" , removeBackspace ? item.Trim() : item);
}
return StringHelper.SplitString(arrayStr.Remove(arrayStr.Length - 1, 1).ToString(), "_" );
}
return array;
}
/// <summary>
/// 移除数组中的指定项
/// </summary>
/// <param name="array">源数组</param>
/// <returns></returns>
public static string [] RemoveArrayItem( string [] array)
{
return RemoveArrayItem(array, "" , true , false );
}
/// <summary>
/// 移除字符串中的指定项
/// </summary>
/// <param name="s">源字符串</param>
/// <param name="splitStr">分割字符串</param>
/// <returns></returns>
public static string [] RemoveStringItem( string s, string splitStr)
{
return RemoveArrayItem(StringHelper.SplitString(s, splitStr), "" , true , false );
}
/// <summary>
/// 移除字符串中的指定项
/// </summary>
/// <param name="s">源字符串</param>
/// <returns></returns>
public static string [] RemoveStringItem( string s)
{
return RemoveArrayItem(StringHelper.SplitString(s), "" , true , false );
}
/// <summary>
/// 移除数组中的重复项
/// </summary>
/// <returns></returns>
public static int [] RemoveRepeaterItem( int [] array)
{
if (array == null || array.Length < 2)
return array;
Array.Sort(array);
int length = 1;
for ( int i = 1; i < array.Length; i++)
{
if (array[i] != array[i - 1])
length++;
}
int [] uniqueArray = new int [length];
uniqueArray[0] = array[0];
int j = 1;
for ( int i = 1; i < array.Length; i++)
if (array[i] != array[i - 1])
uniqueArray[j++] = array[i];
return uniqueArray;
}
/// <summary>
/// 移除数组中的重复项
/// </summary>
/// <returns></returns>
public static string [] RemoveRepeaterItem( string [] array)
{
if (array == null || array.Length < 2)
return array;
Array.Sort(array);
int length = 1;
for ( int i = 1; i < array.Length; i++)
{
if (array[i] != array[i - 1])
length++;
}
string [] uniqueArray = new string [length];
uniqueArray[0] = array[0];
int j = 1;
for ( int i = 1; i < array.Length; i++)
if (array[i] != array[i - 1])
uniqueArray[j++] = array[i];
return uniqueArray;
}
/// <summary>
/// 去除字符串中的重复元素
/// </summary>
/// <returns></returns>
public static string GetUniqueString( string s)
{
return GetUniqueString(s, "," );
}
/// <summary>
/// 去除字符串中的重复元素
/// </summary>
/// <returns></returns>
public static string GetUniqueString( string s, string splitStr)
{
return ObjectArrayToString(RemoveRepeaterItem(StringHelper.SplitString(s, splitStr)), splitStr);
}
#endregion
/// <summary>
/// 去除字符串首尾处的空格、回车、换行符、制表符
/// </summary>
public static string TBBRTrim( string str)
{
if (! string .IsNullOrEmpty(str))
return str.Trim().Trim( '\r' ).Trim( '\n' ).Trim( '\t' );
return string .Empty;
}
/// <summary>
/// 去除字符串中的空格、回车、换行符、制表符
/// </summary>
public static string ClearTBBR( string str)
{
if (! string .IsNullOrEmpty(str))
return _tbbrRegex.Replace(str, "" );
return string .Empty;
}
/// <summary>
/// 删除字符串中的空行
/// </summary>
/// <returns></returns>
public static string DeleteNullOrSpaceRow( string s)
{
if ( string .IsNullOrEmpty(s))
return "" ;
string [] tempArray = StringHelper.SplitString(s, "\r\n" );
StringBuilder result = new StringBuilder();
foreach ( string item in tempArray)
{
if (! string .IsNullOrWhiteSpace(item))
result.AppendFormat( "{0}\r\n" , item);
}
if (result.Length > 0)
result.Remove(result.Length - 2, 2);
return result.ToString();
}
/// <summary>
/// 获得指定数量的html空格
/// </summary>
/// <returns></returns>
public static string GetHtmlBS( int count)
{
if (count == 1)
return " " ;
else if (count == 2)
return " " ;
else if (count == 3)
return " " ;
else
{
StringBuilder result = new StringBuilder();
for ( int i = 0; i < count; i++)
result.Append( " " );
return result.ToString();
}
}
/// <summary>
/// 获得指定数量的htmlSpan元素
/// </summary>
/// <returns></returns>
public static string GetHtmlSpan( int count)
{
if (count <= 0)
return "" ;
if (count == 1)
return "<span></span>" ;
else if (count == 2)
return "<span></span><span></span>" ;
else if (count == 3)
return "<span></span><span></span><span></span>" ;
else
{
StringBuilder result = new StringBuilder();
for ( int i = 0; i < count; i++)
result.Append( "<span></span>" );
return result.ToString();
}
}
/// <summary>
///获得邮箱提供者
/// </summary>
/// <param name="email">邮箱</param>
/// <returns></returns>
public static string GetEmailProvider( string email)
{
int index = email.LastIndexOf( '@' );
if (index > 0)
return email.Substring(index + 1);
return string .Empty;
}
/// <summary>
/// 转义正则表达式
/// </summary>
public static string EscapeRegex( string s)
{
string [] oList = { "\\" , "." , "+" , "*" , "?" , "{" , "}" , "[" , "^" , "]" , "$" , "(" , ")" , "=" , "!" , "<" , ">" , "|" , ":" };
string [] eList = { "\\\\" , "\\." , "\\+" , "\\*" , "\\?" , "\\{" , "\\}" , "\\[" , "\\^" , "\\]" , "\\$" , "\\(" , "\\)" , "\\=" , "\\!" , "\\<" , "\\>" , "\\|" , "\\:" };
for ( int i = 0; i < oList.Length; i++)
s = s.Replace(oList[i], eList[i]);
return s;
}
/// <summary>
/// 将ip地址转换成long类型
/// </summary>
/// <param name="ip">ip</param>
/// <returns></returns>
public static long ConvertIPToLong( string ip)
{
string [] ips = ip.Split( '.' );
long number = 16777216L * long .Parse(ips[0]) + 65536L * long .Parse(ips[1]) + 256 * long .Parse(ips[2]) + long .Parse(ips[3]);
return number;
}
/// <summary>
/// 隐藏邮箱
/// </summary>
public static string HideEmail( string email)
{
int index = email.LastIndexOf( '@' );
if (index == 1)
return "*" + email.Substring(index);
if (index == 2)
return email[0] + "*" + email.Substring(index);
StringBuilder sb = new StringBuilder();
sb.Append(email.Substring(0, 2));
int count = index - 2;
while (count > 0)
{
sb.Append( "*" );
count--;
}
sb.Append(email.Substring(index));
return sb.ToString();
}
/// <summary>
/// 隐藏手机
/// </summary>
public static string HideMobile( string mobile)
{
if (mobile != null && mobile.Length > 10)
return mobile.Substring(0, 3) + "*****" + mobile.Substring(8);
return string .Empty;
}
/// <summary>
/// 数据转换为列表
/// </summary>
/// <param name="array">数组</param>
/// <returns></returns>
public static List<T> ArrayToList<T>(T[] array)
{
List<T> list = new List<T>(array.Length);
foreach (T item in array)
list.Add(item);
return list;
}
/// <summary>
/// DataTable转化为List
/// </summary>
/// <param name="dt">DataTable</param>
/// <returns></returns>
public static List<Dictionary< string , object >> DataTableToList(DataTable dt)
{
int columnCount = dt.Columns.Count;
List<Dictionary< string , object >> list = new List<Dictionary< string , object >>(dt.Rows.Count);
foreach (DataRow dr in dt.Rows)
{
Dictionary< string , object > item = new Dictionary< string , object >(columnCount);
for ( int i = 0; i < columnCount; i++)
{
item.Add(dt.Columns[i].ColumnName, dr[i]);
}
list.Add(item);
}
return list;
}
}
|
验证数据帮助类
using System; using System.Text.RegularExpressions; namespace ZMM.Core { /// <summary> /// 验证帮助类 /// </summary> public class ValidateHelper { //邮件正则表达式 private static Regex _emailregex = new Regex(@"^[a-z0-9]([a-z0-9]*[-_]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[\.][a-z]{2,3}([\.][a-z]{2})?$", RegexOptions.IgnoreCase); //手机号正则表达式 private static Regex _mobileregex = new Regex("^(13|15|17|18)[0-9]{9}$"); //固话号正则表达式 private static Regex _phoneregex = new Regex(@"^(\d{3,4}-?)?\d{7,8}$"); //IP正则表达式 private static Regex _ipregex = new Regex(@"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$"); //日期正则表达式 private static Regex _dateregex = new Regex(@"(\d{4})-(\d{1,2})-(\d{1,2})"); //数值(包括整数和小数)正则表达式 private static Regex _numericregex = new Regex(@"^[-]?[0-9]+(\.[0-9]+)?$"); //邮政编码正则表达式 private static Regex _zipcoderegex = new Regex(@"^\d{6}$"); /// <summary> /// 是否为邮箱名 /// </summary> public static bool IsEmail(string s) { if (string.IsNullOrEmpty(s)) return true; return _emailregex.IsMatch(s); } /// <summary> /// 是否为手机号 /// </summary> public static bool IsMobile(string s) { if (string.IsNullOrEmpty(s)) return true; return _mobileregex.IsMatch(s); } /// <summary> /// 是否为固话号 /// </summary> public static bool IsPhone(string s) { if (string.IsNullOrEmpty(s)) return true; return _phoneregex.IsMatch(s); } /// <summary> /// 是否为IP /// </summary> public static bool IsIP(string s) { return _ipregex.IsMatch(s); } /// <summary> /// 是否是身份证号 /// </summary> public static bool IsIdCard(string id) { if (string.IsNullOrEmpty(id)) return true; if (id.Length == 18) return CheckIDCard18(id); else if (id.Length == 15) return CheckIDCard15(id); else return false; } /// <summary> /// 是否为18位身份证号 /// </summary> private static bool CheckIDCard18(string Id) { long n = 0; if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false) return false;//数字验证 string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91"; if (address.IndexOf(Id.Remove(2)) == -1) return false;//省份验证 string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-"); DateTime time = new DateTime(); if (DateTime.TryParse(birth, out time) == false) return false;//生日验证 string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(','); string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(','); char[] Ai = Id.Remove(17).ToCharArray(); int sum = 0; for (int i = 0; i < 17; i++) sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString()); int y = -1; Math.DivRem(sum, 11, out y); if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower()) return false;//校验码验证 return true;//符合GB11643-1999标准 } /// <summary> /// 是否为15位身份证号 /// </summary> private static bool CheckIDCard15(string Id) { long n = 0; if (long.TryParse(Id, out n) == false || n < Math.Pow(10, 14)) return false;//数字验证 string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91"; if (address.IndexOf(Id.Remove(2)) == -1) return false;//省份验证 string birth = Id.Substring(6, 6).Insert(4, "-").Insert(2, "-"); DateTime time = new DateTime(); if (DateTime.TryParse(birth, out time) == false) return false;//生日验证 return true;//符合15位身份证标准 } /// <summary> /// 是否为日期 /// </summary> public static bool IsDate(string s) { return _dateregex.IsMatch(s); } /// <summary> /// 是否是数值(包括整数和小数) /// </summary> public static bool IsNumeric(string numericStr) { return _numericregex.IsMatch(numericStr); } /// <summary> /// 是否为邮政编码 /// </summary> public static bool IsZipCode(string s) { if (string.IsNullOrEmpty(s)) return true; return _zipcoderegex.IsMatch(s); } /// <summary> /// 是否是图片文件名 /// </summary> /// <returns> </returns> public static bool IsImgFileName(string fileName) { if (fileName.IndexOf(".") == -1) return false; string tempFileName = fileName.Trim().ToLower(); string extension = tempFileName.Substring(tempFileName.LastIndexOf(".")); return extension == ".png" || extension == ".bmp" || extension == ".jpg" || extension == ".jpeg" || extension == ".gif"; } /// <summary> /// 是否是文件名word /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static bool IsFile(string fileName) { if (fileName.IndexOf(".") == -1) return false; string tempFileName = fileName.Trim().ToLower(); string extension = tempFileName.Substring(tempFileName.LastIndexOf(".")); return extension == ".doc" || extension == ".docx" || extension == ".xls" || extension == ".xlsx" || extension == ".txt"; } /// <summary> /// 判断一个ip是否在另一个ip内 /// </summary> /// <param name="sourceIP">检测ip</param> /// <param name="targetIP">匹配ip</param> /// <returns></returns> public static bool InIP(string sourceIP, string targetIP) { if (string.IsNullOrEmpty(sourceIP) || string.IsNullOrEmpty(targetIP)) return false; string[] sourceIPBlockList = StringHelper.SplitString(sourceIP, @"."); string[] targetIPBlockList = StringHelper.SplitString(targetIP, @"."); int sourceIPBlockListLength = sourceIPBlockList.Length; for (int i = 0; i < sourceIPBlockListLength; i++) { if (targetIPBlockList[i] == "*") return true; if (sourceIPBlockList[i] != targetIPBlockList[i]) { return false; } else { if (i == 3) return true; } } return false; } /// <summary> /// 判断一个ip是否在另一个ip内 /// </summary> /// <param name="sourceIP">检测ip</param> /// <param name="targetIPList">匹配ip列表</param> /// <returns></returns> public static bool InIPList(string sourceIP, string[] targetIPList) { if (targetIPList != null && targetIPList.Length > 0) { foreach (string targetIP in targetIPList) { if (InIP(sourceIP, targetIP)) return true; } } return false; } /// <summary> /// 判断一个ip是否在另一个ip内 /// </summary> /// <param name="sourceIP">检测ip</param> /// <param name="targetIPStr">匹配ip</param> /// <returns></returns> public static bool InIPList(string sourceIP, string targetIPStr) { string[] targetIPList = StringHelper.SplitString(targetIPStr, "\n"); return InIPList(sourceIP, targetIPList); } /// <summary> /// 判断当前时间是否在指定的时间段内 /// </summary> /// <param name="periodList">指定时间段</param> /// <param name="liePeriod">所处时间段</param> /// <returns></returns> public static bool BetweenPeriod(string[] periodList, out string liePeriod) { if (periodList != null && periodList.Length > 0) { DateTime startTime; DateTime endTime; DateTime nowTime = DateTime.Now; DateTime nowDate = nowTime.Date; foreach (string period in periodList) { int index = period.IndexOf("-"); startTime = TypeHelper.StringToDateTime(period.Substring(0, index)); endTime = TypeHelper.StringToDateTime(period.Substring(index + 1)); if (startTime < endTime) { if (nowTime > startTime && nowTime < endTime) { liePeriod = period; return true; } } else { if ((nowTime > startTime && nowTime < nowDate.AddDays(1)) || (nowTime < endTime)) { liePeriod = period; return true; } } } } liePeriod = string.Empty; return false; } /// <summary> /// 判断当前时间是否在指定的时间段内 /// </summary> /// <param name="periodStr">指定时间段</param> /// <param name="liePeriod">所处时间段</param> /// <returns></returns> public static bool BetweenPeriod(string periodStr, out string liePeriod) { string[] periodList = StringHelper.SplitString(periodStr, "\n"); return BetweenPeriod(periodList, out liePeriod); } /// <summary> /// 判断当前时间是否在指定的时间段内 /// </summary> /// <param name="periodList">指定时间段</param> /// <returns></returns> public static bool BetweenPeriod(string periodList) { string liePeriod = string.Empty; return BetweenPeriod(periodList, out liePeriod); } /// <summary> /// 是否是数值(包括整数和小数) /// </summary> public static bool IsNumericArray(string[] numericStrList) { if (numericStrList != null && numericStrList.Length > 0) { foreach (string numberStr in numericStrList) { if (!IsNumeric(numberStr)) return false; } return true; } return false; } /// <summary> /// 是否是数值(包括整数和小数) /// </summary> public static bool IsNumericRule(string numericRuleStr, string splitChar) { return IsNumericArray(StringHelper.SplitString(numericRuleStr, splitChar)); } /// <summary> /// 是否是数值(包括整数和小数) /// </summary> public static bool IsNumericRule(string numericRuleStr) { return IsNumericRule(numericRuleStr, ","); } } }
IO帮助类
using System; using System.IO; using System.Web; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Drawing2D; using System.Xml.Serialization; namespace ZMM.Core { /// <summary> /// IO帮助类 /// </summary> public class IOHelper { //是否已经加载了JPEG编码解码器 private static bool _isloadjpegcodec = false; //当前系统安装的JPEG编码解码器 private static ImageCodecInfo _jpegcodec = null; /// <summary> /// 获得文件物理路径 /// </summary> /// <returns></returns> public static string GetMapPath(string path) { if (HttpContext.Current != null) { return HttpContext.Current.Server.MapPath(path); } else { return System.Web.Hosting.HostingEnvironment.MapPath(path); } } #region 序列化 /// <summary> /// XML序列化 /// </summary> /// <param name="obj">序列对象</param> /// <param name="filePath">XML文件路径</param> /// <returns>是否成功</returns> public static bool SerializeToXml(object obj, string filePath) { bool result = false; FileStream fs = null; try { fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); XmlSerializer serializer = new XmlSerializer(obj.GetType()); serializer.Serialize(fs, obj); result = true; } catch (Exception ex) { throw ex; } finally { if (fs != null) fs.Close(); } return result; } /// <summary> /// XML反序列化 /// </summary> /// <param name="type">目标类型(Type类型)</param> /// <param name="filePath">XML文件路径</param> /// <returns>序列对象</returns> public static object DeserializeFromXML(Type type, string filePath) { FileStream fs = null; try { fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); XmlSerializer serializer = new XmlSerializer(type); return serializer.Deserialize(fs); } catch (Exception ex) { throw ex; } finally { if (fs != null) fs.Close(); } } #endregion #region 水印,缩略图 /// <summary> /// 获得当前系统安装的JPEG编码解码器 /// </summary> /// <returns></returns> public static ImageCodecInfo GetJPEGCodec() { if (_isloadjpegcodec == true) return _jpegcodec; ImageCodecInfo[] codecsList = ImageCodecInfo.GetImageEncoders(); foreach (ImageCodecInfo codec in codecsList) { if (codec.MimeType.IndexOf("jpeg") > -1) { _jpegcodec = codec; break; } } _isloadjpegcodec = true; return _jpegcodec; } /// <summary> /// 生成缩略图 /// </summary> /// <param name="imagePath">图片路径</param> /// <param name="thumbPath">缩略图路径</param> /// <param name="width">缩略图宽度</param> /// <param name="height">缩略图高度</param> /// <param name="mode">生成缩略图的方式</param> public static void GenerateThumb(string imagePath, string thumbPath, int width, int height, string mode) { Image image = Image.FromFile(imagePath); string extension = imagePath.Substring(imagePath.LastIndexOf(".")).ToLower(); ImageFormat imageFormat = null; switch (extension) { case ".jpg": case ".jpeg": imageFormat = ImageFormat.Jpeg; break; case ".bmp": imageFormat = ImageFormat.Bmp; break; case ".png": imageFormat = ImageFormat.Png; break; case ".gif": imageFormat = ImageFormat.Gif; break; default: imageFormat = ImageFormat.Jpeg; break; } int toWidth = width > 0 ? width : image.Width; int toHeight = height > 0 ? height : image.Height; int x = 0; int y = 0; int ow = image.Width; int oh = image.Height; switch (mode) { case "HW"://指定高宽缩放(可能变形) break; case "W"://指定宽,高按比例 toHeight = image.Height * width / image.Width; break; case "H"://指定高,宽按比例 toWidth = image.Width * height / image.Height; break; case "Cut"://指定高宽裁减(不变形) if ((double)image.Width / (double)image.Height > (double)toWidth / (double)toHeight) { oh = image.Height; ow = image.Height * toWidth / toHeight; y = 0; x = (image.Width - ow) / 2; } else { ow = image.Width; oh = image.Width * height / toWidth; x = 0; y = (image.Height - oh) / 2; } break; default: break; } //新建一个bmp Image bitmap = new Bitmap(toWidth, toHeight); //新建一个画板 Graphics g = Graphics.FromImage(bitmap); //设置高质量插值法 g.InterpolationMode = InterpolationMode.High; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = SmoothingMode.HighQuality; //清空画布并以透明背景色填充 g.Clear(Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(image, new Rectangle(0, 0, toWidth, toHeight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel); try { bitmap.Save(thumbPath, imageFormat); } catch (Exception ex) { throw ex; } finally { if (g != null) g.Dispose(); if (bitmap != null) bitmap.Dispose(); if (image != null) image.Dispose(); } } /// <summary> /// 生成图片水印 /// </summary> /// <param name="originalPath">源图路径</param> /// <param name="watermarkPath">水印图片路径</param> /// <param name="targetPath">保存路径</param> /// <param name="position">位置</param> /// <param name="opacity">透明度</param> /// <param name="quality">质量</param> public static void GenerateImageWatermark(string originalPath, string watermarkPath, string targetPath, int position, int opacity, int quality) { Image originalImage = null; Image watermarkImage = null; //图片属性 ImageAttributes attributes = null; //画板 Graphics g = null; try { originalImage = Image.FromFile(originalPath); watermarkImage = new Bitmap(watermarkPath); if (watermarkImage.Height >= originalImage.Height || watermarkImage.Width >= originalImage.Width) { originalImage.Save(targetPath); return; } if (quality < 0 || quality > 100) quality = 80; //水印透明度 float iii; if (opacity > 0 && opacity <= 10) iii = (float)(opacity / 10.0F); else iii = 0.5F; //水印位置 int x = 0; int y = 0; switch (position) { case 1: x = (int)(originalImage.Width * (float).01); y = (int)(originalImage.Height * (float).01); break; case 2: x = (int)((originalImage.Width * (float).50) - (watermarkImage.Width / 2)); y = (int)(originalImage.Height * (float).01); break; case 3: x = (int)((originalImage.Width * (float).99) - (watermarkImage.Width)); y = (int)(originalImage.Height * (float).01); break; case 4: x = (int)(originalImage.Width * (float).01); y = (int)((originalImage.Height * (float).50) - (watermarkImage.Height / 2)); break; case 5: x = (int)((originalImage.Width * (float).50) - (watermarkImage.Width / 2)); y = (int)((originalImage.Height * (float).50) - (watermarkImage.Height / 2)); break; case 6: x = (int)((originalImage.Width * (float).99) - (watermarkImage.Width)); y = (int)((originalImage.Height * (float).50) - (watermarkImage.Height / 2)); break; case 7: x = (int)(originalImage.Width * (float).01); y = (int)((originalImage.Height * (float).99) - watermarkImage.Height); break; case 8: x = (int)((originalImage.Width * (float).50) - (watermarkImage.Width / 2)); y = (int)((originalImage.Height * (float).99) - watermarkImage.Height); break; case 9: x = (int)((originalImage.Width * (float).99) - (watermarkImage.Width)); y = (int)((originalImage.Height * (float).99) - watermarkImage.Height); break; } //颜色映射表 ColorMap colorMap = new ColorMap(); colorMap.OldColor = Color.FromArgb(255, 0, 255, 0); colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); ColorMap[] newColorMap = { colorMap }; //颜色变换矩阵,iii是设置透明度的范围0到1中的单精度类型 float[][] newColorMatrix ={ new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, new float[] {0.0f, 0.0f, 0.0f, iii, 0.0f}, new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f} }; //定义一个 5 x 5 矩阵 ColorMatrix matrix = new ColorMatrix(newColorMatrix); //图片属性 attributes = new ImageAttributes(); attributes.SetRemapTable(newColorMap, ColorAdjustType.Bitmap); attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); //画板 g = Graphics.FromImage(originalImage); //绘制水印 g.DrawImage(watermarkImage, new Rectangle(x, y, watermarkImage.Width, watermarkImage.Height), 0, 0, watermarkImage.Width, watermarkImage.Height, GraphicsUnit.Pixel, attributes); //保存图片 EncoderParameters encoderParams = new EncoderParameters(); encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, new long[] { quality }); if (GetJPEGCodec() != null) originalImage.Save(targetPath, _jpegcodec, encoderParams); else originalImage.Save(targetPath); } catch (Exception ex) { throw ex; } finally { if (g != null) g.Dispose(); if (attributes != null) attributes.Dispose(); if (watermarkImage != null) watermarkImage.Dispose(); if (originalImage != null) originalImage.Dispose(); } } /// <summary> /// 生成文字水印 /// </summary> /// <param name="originalPath">源图路径</param> /// <param name="targetPath">保存路径</param> /// <param name="text">水印文字</param> /// <param name="textSize">文字大小</param> /// <param name="textFont">文字字体</param> /// <param name="position">位置</param> /// <param name="quality">质量</param> public static void GenerateTextWatermark(string originalPath, string targetPath, string text, int textSize, string textFont, int position, int quality) { Image originalImage = null; //画板 Graphics g = null; try { originalImage = Image.FromFile(originalPath); //画板 g = Graphics.FromImage(originalImage); if (quality < 0 || quality > 100) quality = 80; Font font = new Font(textFont, textSize, FontStyle.Regular, GraphicsUnit.Pixel); SizeF sizePair = g.MeasureString(text, font); float x = 0; float y = 0; switch (position) { case 1: x = (float)originalImage.Width * (float).01; y = (float)originalImage.Height * (float).01; break; case 2: x = ((float)originalImage.Width * (float).50) - (sizePair.Width / 2); y = (float)originalImage.Height * (float).01; break; case 3: x = ((float)originalImage.Width * (float).99) - sizePair.Width; y = (float)originalImage.Height * (float).01; break; case 4: x = (float)originalImage.Width * (float).01; y = ((float)originalImage.Height * (float).50) - (sizePair.Height / 2); break; case 5: x = ((float)originalImage.Width * (float).50) - (sizePair.Width / 2); y = ((float)originalImage.Height * (float).50) - (sizePair.Height / 2); break; case 6: x = ((float)originalImage.Width * (float).99) - sizePair.Width; y = ((float)originalImage.Height * (float).50) - (sizePair.Height / 2); break; case 7: x = (float)originalImage.Width * (float).01; y = ((float)originalImage.Height * (float).99) - sizePair.Height; break; case 8: x = ((float)originalImage.Width * (float).50) - (sizePair.Width / 2); y = ((float)originalImage.Height * (float).99) - sizePair.Height; break; case 9: x = ((float)originalImage.Width * (float).99) - sizePair.Width; y = ((float)originalImage.Height * (float).99) - sizePair.Height; break; } g.DrawString(text, font, new SolidBrush(Color.White), x + 1, y + 1); g.DrawString(text, font, new SolidBrush(Color.Black), x, y); //保存图片 EncoderParameters encoderParams = new EncoderParameters(); encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, new long[] { quality }); if (GetJPEGCodec() != null) originalImage.Save(targetPath, _jpegcodec, encoderParams); else originalImage.Save(targetPath); } catch (Exception ex) { throw ex; } finally { if (g != null) g.Dispose(); if (originalImage != null) originalImage.Dispose(); } } #endregion } }
c# Lambda操作类封装
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace EasyFrame.Common { public static class LambdaCommon { #region 表达式工具 /// <summary> /// 相当于&&操作 /// ——Author:hellthinker /// </summary> /// <param name="thisFilter">已生成的过滤条件</param> /// <param name="otherFilter">未生成的过滤条件</param> /// <returns>新的过滤</returns> public static Expression GotoAndAlso(this Expression thisFilter, Expression otherFilter) { return Expression.AndAlso(thisFilter, otherFilter); } /// <summary> /// 相当于||操作 /// ——Author:hellthinker /// </summary> /// <param name="thisFilter">已生成的过滤条件</param> /// <param name="otherFilter">未生成的过滤条件</param> /// <returns>新的过滤</returns> public static Expression GotoOrElse(this Expression thisFilter, Expression otherFilter) { return Expression.OrElse(thisFilter, otherFilter); } /// <summary> /// 相当于==操作 /// ——Author:hellthinker /// </summary> /// <param name="thisParameterExpression">查询对象</param> /// <param name="propertieName">属性名称</param> /// <param name="propertieValue">属性值</param> /// <returns>新的过滤</returns> public static Expression GotoEqual(this ParameterExpression thisParameterExpression, string propertieName, object propertieValue) { return Expression.Equal(Expression.Property(thisParameterExpression, propertieName), Expression.Constant(propertieValue)); } /// <summary> /// 相当于>=操作 /// ——Author:hellthinker /// </summary> /// <param name="thisParameterExpression">查询对象</param> /// <param name="propertieName">属性名称</param> /// <param name="propertieValue">属性值</param> /// <returns>新的过滤</returns> public static Expression GotoGreaterThanOrEqual<T>(this ParameterExpression thisParameterExpression, string propertieName, object propertieValue) { //大于或等于 return Expression.GreaterThanOrEqual(Expression.Property(thisParameterExpression, propertieName), Expression.Constant(propertieValue, typeof(T))); } /// <summary> /// 相当于小于等于操作 /// ——Author:hellthinker /// </summary> /// <param name="thisParameterExpression">查询对象</param> /// <param name="propertieName">属性名称</param> /// <param name="propertieValue">属性值</param> /// <returns>新的过滤</returns> public static Expression GotoLessThanOrEqual<T>(this ParameterExpression thisParameterExpression, string propertieName, object propertieValue) { //小于或等于 return Expression.LessThanOrEqual(Expression.Property(thisParameterExpression, propertieName), Expression.Constant(propertieValue, typeof(T))); } /// <summary> /// 相当于!=操作 /// ——Author:hellthinker /// </summary> /// <param name="thisParameterExpression">查询对象</param> /// <param name="propertieName">属性名称</param> /// <param name="propertieValue">属性值</param> /// <returns>新的过滤</returns> public static Expression GotoNotEqual(this ParameterExpression thisParameterExpression, string propertieName, object propertieValue) { return Expression.NotEqual(Expression.Property(thisParameterExpression, propertieName), Expression.Constant(propertieValue)); } /// <summary> /// 相当于>=操作 /// ——Author:hellthinker /// </summary> /// <param name="thisParameterExpression">查询对象</param> /// <param name="propertieName">属性名称</param> /// <param name="propertieValue">属性值</param> /// <returns>新的过滤</returns> public static Expression GotoGreaterThanOrEqual(this ParameterExpression thisParameterExpression, string propertieName, object propertieValue) { //大于或等于 return Expression.GreaterThanOrEqual(Expression.Property(thisParameterExpression, propertieName), Expression.Constant(propertieValue)); } /// <summary> /// 相当于>操作 /// ——Author:hellthinker /// </summary> /// <param name="thisParameterExpression">查询对象</param> /// <param name="propertieName">属性名称</param> /// <param name="propertieValue">属性值</param> /// <returns>新的过滤</returns> public static Expression GotoGreaterThan<T>(this ParameterExpression thisParameterExpression, string propertieName, object propertieValue) { //大于 return Expression.GreaterThan(Expression.Property(thisParameterExpression, propertieName), Expression.Constant(propertieValue, typeof(T))); } /// <summary> /// 相当于小于操作 /// ——Author:hellthinker /// </summary> /// <param name="thisParameterExpression">查询对象</param> /// <param name="propertieName">属性名称</param> /// <param name="propertieValue">属性值</param> /// <returns>新的过滤</returns> public static Expression GotoLessThan<T>(this ParameterExpression thisParameterExpression, string propertieName, object propertieValue) { //小于 return Expression.LessThan(Expression.Property(thisParameterExpression, propertieName), Expression.Constant(propertieValue, typeof(T))); } /// <summary> /// 相当于>=操作 /// ——Author:hellthinker /// </summary> /// <param name="thisParameterExpression">查询对象</param> /// <param name="propertieName">属性名称</param> /// <param name="propertieValue">属性值</param> /// <returns>新的过滤</returns> public static Expression GotoGreaterThanOrEqualByDateTime(this ParameterExpression thisParameterExpression, string propertieName, object propertieValue) { //大于或等于 return Expression.GreaterThanOrEqual(Expression.Property(thisParameterExpression, propertieName), Expression.Constant(propertieValue, typeof(DateTime?))); } /// <summary> /// 字符串包含 /// </summary> /// <param name="thisParameterExpression">查询对象</param> /// <param name="propertieName">属性名称</param> /// <param name="propertieValue">属性值</param> /// <returns>新的过滤</returns> public static Expression GotoContains(this ParameterExpression thisParameterExpression, string propertieName, object propertieValue) { return Expression.Call(Expression.Property(thisParameterExpression, propertieName), typeof(string).GetMethod("Contains"), Expression.Constant(propertieValue)); } /// <summary> /// 相当于小于或等于操作 /// ——Author:hellthinker /// </summary> /// <param name="thisParameterExpression">查询对象</param> /// <param name="propertieName">属性名称</param> /// <param name="propertieValue">属性值</param> /// <returns>新的过滤</returns> public static Expression GotoLessThanOrEqualByDateTime(this ParameterExpression thisParameterExpression, string propertieName, object propertieValue) { //小于或等于 return Expression.LessThanOrEqual(Expression.Property(thisParameterExpression, propertieName), Expression.Constant(propertieValue, typeof(DateTime?))); } /// <summary> /// 相当于>操作 /// ——Author:hellthinker /// </summary> /// <param name="thisParameterExpression">查询对象</param> /// <param name="propertieName">属性名称</param> /// <param name="propertieValue">属性值</param> /// <returns>新的过滤</returns> public static Expression GotoGreaterThanByDateTime(this ParameterExpression thisParameterExpression, string propertieName, object propertieValue) { //大于 return Expression.GreaterThan(Expression.Property(thisParameterExpression, propertieName), Expression.Constant(propertieValue, typeof(DateTime?))); } /// <summary> /// 相当于小于操作 /// ——Author:hellthinker /// </summary> /// <param name="thisParameterExpression">查询对象</param> /// <param name="propertieName">属性名称</param> /// <param name="propertieValue">属性值</param> /// <returns>新的过滤</returns> public static Expression GotoLessThanByDateTime(this ParameterExpression thisParameterExpression, string propertieName, object propertieValue) { //小于 return Expression.LessThan(Expression.Property(thisParameterExpression, propertieName), Expression.Constant(propertieValue, typeof(DateTime?))); } /// <summary> /// 包含操作 相当余 a=> arr.Contains(a.ID) /// </summary> /// <param name="thisParameterExpression"></param> /// <param name="propertieName"></param> /// <param name="propertieValue"></param> /// <returns></returns> public static Expression ContainsOperations(this ParameterExpression thisParameterExpression, string propertieName, object propertieValue) { MethodInfo method = null; MemberExpression member = Expression.Property(thisParameterExpression, propertieName); var containsMethods = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(m => m.Name == "Contains"); foreach (var m in containsMethods) { if (m.GetParameters().Count() == 2) { method = m; break; } } method = method.MakeGenericMethod(member.Type); var exprContains = Expression.Call(method, new Expression[] { Expression.Constant(propertieValue), member }); return exprContains; } /// <summary> /// 包含操作 相当于 a=>a.ID.Contains(key) /// </summary> /// <param name="thisParameterExpression"></param> /// <param name="propertieName"></param> /// <param name="propertieValue"></param> /// <returns></returns> public static Expression Contains(this ParameterExpression thisParameterExpression, string propertieName, object propertieValue) { var propertyExp = Expression.Property(thisParameterExpression, propertieName); MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) }); var someValue = Expression.Constant(propertieValue, typeof(string)); var containsMethodExp = Expression.Call(propertyExp, method, someValue); return containsMethodExp; } #endregion } }
C# -- 使用反射(Reflect)获取dll文件中的类型并调用方法
使用反射(Reflect)获取dll文件中的类型并调用方法
需引用:System.Reflection;
1. 使用反射(Reflect)获取dll文件中的类型并调用方法(入门案例)
1 static void Main(string[] args) 2 { 3 //dll文件路径 4 string path = @"D:\VS2015Project\001\Computer\bin\Debug\computer.dll"; 5 6 //加载dll文件 7 Assembly asm = Assembly.LoadFile(path); 8 9 //获取类 10 Type type = asm.GetType("Computer.Computer"); 11 12 //创建该类型的实例 13 object obj = Activator.CreateInstance(type); 14 15 //获取该类的方法 16 MethodInfo mf = type.GetMethod("ShowDrives"); 17 18 //调用方法 19 mf.Invoke(obj, null); 20 21 Console.ReadKey(); 22 }
2. 生成类库(computer.dll)的computer.cs文件代码
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Text; 6 7 8 namespace Computer 9 { 10 public class Computer 11 { 12 private DriveInfo[] drives; 13 public Computer() 14 { 15 this.drives = DriveInfo.GetDrives(); 16 } 17 public void ShowDrives() 18 { 19 Console.WriteLine("该电脑的磁盘驱动器有:\r\n"); 20 foreach (var item in drives) 21 { 22 Console.WriteLine(item); 23 } 24 } 25 } 26 }
3. 反射调用结果:
C# -- 文件的压缩与解压(GZipStream)
文件的压缩与解压
需引入 System.IO.Compression;
1.C#代码(入门案例)
1 Console.WriteLine("压缩文件..............."); 2 using (FileStream fr = File.OpenRead("d:\\test.txt")) 3 { 4 using (FileStream fw = File.OpenWrite("d:\\test.zip")) 5 { 6 using (GZipStream gz = new GZipStream(fw, CompressionMode.Compress)) 7 { 8 9 byte[] by = new byte[1024 * 1024]; 10 int r = fr.Read(by, 0, by.Length); 11 while (r > 0) 12 { 13 gz.Write(by, 0, r); 14 r = fr.Read(by, 0, r); 15 } 16 } 17 } 18 } 19 Console.WriteLine("压缩完成。"); 20 21 22 Console.WriteLine("解压文件..............."); 23 using (FileStream fr = File.OpenRead("d:\\test.zip")) 24 { 25 using (GZipStream gz = new GZipStream(fr, CompressionMode.Decompress)) 26 { 27 using (FileStream fw = File.OpenWrite("d:\\test2.txt")) 28 { 29 30 byte[] by = new byte[1024 * 1024]; 31 int r = gz.Read(by, 0, by.Length); 32 while (r > 0) 33 { 34 fw.Write(by, 0, r); 35 r = gz.Read(by, 0, r); 36 } 37 } 38 } 39 } 40 Console.WriteLine("解压完成。"); 41 42 Console.ReadKey();
2. 运行结果