1 using System;
2 using System.Collections;
3 using System.Data;
4 using System.Diagnostics;
5 using System.IO;
6 using System.Net;
7 using System.Net.NetworkInformation;
8 using System.Text;
9 using System.Text.RegularExpressions;
10 using System.Windows.Media;
11 using System.Windows.Media.Imaging;
12
13 namespace TeachingSystem.Common
14 {
15 /// <summary>
16 /// 通用方法帮助类
17 /// W
18 /// </summary>
19 public class HelpCommon
20 {
21 public static string Version { get; set; }
22 public static int TimeOutValue = 5000;
23 public static event EventHandler eventUrlIsExist;
24 public static event EventHandler eventPing;
25 /// <summary>
26 /// 运行Cmd命令
27 /// </summary>
28 /// <param name="command"></param>
29 /// <returns></returns>
30 public static string RunCmd(string command)
31 {
32 //实例一个Process类,启动一个独立进程
33 Process p = new Process();
34 //Process类有一个StartInfo属性
35 //设定程序名
36 p.StartInfo.FileName = "cmd.exe";
37 //设定程式执行参数,c代表执行参数指定的命令后关闭cmd.exe, /k参数则不关闭cmd.exe
38 p.StartInfo.Arguments = "/c " + command;
39 //关闭Shell的使用
40 p.StartInfo.UseShellExecute = false;
41 //重定向标准输入
42 p.StartInfo.RedirectStandardInput = true;
43 p.StartInfo.RedirectStandardOutput = true;
44 //重定向错误输出
45 p.StartInfo.RedirectStandardError = true;
46 //设置不显示窗口
47 p.StartInfo.CreateNoWindow = true;
48 //启动
49 p.Start();
50 //也可以用这种方式输入要执行的命令
51 //不过要记得加上Exit要不然下一行程式执行的时候会当机
52 //p.StandardInput.WriteLine(command);
53 //p.StandardInput.WriteLine("exit");
54 //从输出流取得命令执行结果
55 return p.StandardOutput.ReadToEnd();
56 }
57
58 /// <summary>
59 /// 判断Url是否能访问
60 /// </summary>
61 /// <param name="url"></param>
62 /// <returns></returns>
63 ///
64 public static bool UrlIsExist(String url)
65 {
66 if (PublicVar.NoNet)
67 {
68 if (eventUrlIsExist != null)
69 eventUrlIsExist(false, null);
70 return false;
71 }
72 HttpWebRequest request = null;
73
74 if (request != null)
75 {
76 request.Abort();
77 request = null;
78 }
79 System.Uri u = null;
80 try
81 {
82 u = new Uri(url);
83 }
84 catch
85 {
86 return false;
87 }
88 bool isExist = false;
89 request = System.Net.HttpWebRequest.Create(u) as System.Net.HttpWebRequest;
90 request.Method = "HEAD";
91 request.Timeout = TimeOutValue;
92 try
93 {
94 System.Net.HttpWebResponse s = request.GetResponse() as System.Net.HttpWebResponse;
95 if (s.StatusCode == System.Net.HttpStatusCode.OK)
96 {
97 isExist = true;
98 }
99 }
100 catch (System.Net.WebException x)
101 {
102 try
103 {
104 isExist = ((x.Response as System.Net.HttpWebResponse).StatusCode != System.Net.HttpStatusCode.NotFound);
105 }
106 catch
107 {
108 isExist = (x.Status == System.Net.WebExceptionStatus.Success);
109 }
110 }
111 if (isExist)
112 Console.ForegroundColor = ConsoleColor.Green;
113 else
114 Console.ForegroundColor = ConsoleColor.Red;
115 Console.WriteLine(url + "连接状态" + isExist);
116 Console.ForegroundColor = ConsoleColor.White;
117 if (eventUrlIsExist != null)
118 eventUrlIsExist(isExist, null);
119 return isExist;
120 }
121
122 /// <summary>
123 /// 检查DataTable是否为空
124 /// </summary>
125 /// <param name="DataTable"></param>
126 /// <returns></returns>
127 public static bool CheckDataTable(DataTable DataTable)
128 {
129 if (DataTable != null)
130 {
131 if (DataTable.Rows.Count > 0)
132 return true;
133 else
134 return false;
135 }
136 else
137 return false;
138 }
139
140 /// <summary>
141 /// object转换为String
142 /// </summary>
143 /// <param name="obj"></param>
144 /// <returns></returns>
145 public static string ObjectToString(object obj)
146 {
147 if (obj != null)
148 {
149 string Str = obj.ToString();
150 if (!string.IsNullOrEmpty(Str))
151 return Str;
152 else
153 return string.Empty;
154 }
155 else
156 return string.Empty;
157 }
158
159 /// <summary>
160 /// 验证是否为数字
161 /// </summary>
162 /// <param name="value"></param>
163 /// <returns></returns>
164 public static bool RegexInt(object value)
165 {
166 return new Regex("^[0-9]+$").Match(value.ToString()).Success;
167 }
168
169 /// <summary>
170 /// 验证是否为日期
171 /// </summary>
172 /// <param name="strDate"></param>
173 /// <returns></returns>
174 public static bool IsDate(string strDate)
175 {
176 try
177 {
178 DateTime.Parse(strDate);
179 return true;
180 }
181 catch
182 {
183 return false;
184 }
185 }
186
187 /// <summary>
188 /// 通过系统浏览器打开一个链接
189 /// </summary>
190 /// <param name="Link"></param>
191 public static void OpenLink(string Link)
192 {
193 try
194 {
195 System.Diagnostics.Process.Start(Link);
196 }
197 catch (System.ComponentModel.Win32Exception noBrowser)
198 {
199 if (noBrowser.ErrorCode == -2147467259)
200 throw (noBrowser);
201 }
202 catch (System.Exception other)
203 {
204 throw (other);
205 }
206 }
207
208 /// <summary>
209 /// 日期转星期数字
210 /// </summary>
211 /// <param name="dt"></param>
212 /// <returns></returns>
213 public static int WeekToInt(DateTime dt)
214 {
215 switch (dt.DayOfWeek.ToString())
216 {
217 case "Monday": return 1;
218 case "Tuesday": return 2;
219 case "Wednesday": return 3;
220 case "Thursday": return 4;
221 case "Friday": return 5;
222 case "Saturday": return 6;
223 case "Sunday": return 0;
224 default: return 0;
225 }
226 }
227
228 /// <summary>
229 /// 日期转星期汉字
230 /// </summary>
231 /// <param name="dt"></param>
232 /// <returns></returns>
233 public static string WeekToString(DateTime dt)
234 {
235 switch (dt.DayOfWeek.ToString())
236 {
237 case "Monday": return "一";
238 case "Tuesday": return "二";
239 case "Wednesday": return "三";
240 case "Thursday": return "四";
241 case "Friday": return "五";
242 case "Saturday": return "六";
243 case "Sunday": return "日";
244 default: return "0";
245 }
246 }
247
248 /// <summary>
249 /// 清除HTML代码
250 /// </summary>
251 /// <param name="Htmlstring"></param>
252 /// <returns></returns>
253 public static string NoHTML(string Htmlstring)
254 {
255 Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
256 Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
257 Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
258 Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
259 Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
260 Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
261 Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
262 Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
263 Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
264 Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
265 Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
266 Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
267 Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
268 Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
269 Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
270 Htmlstring = Regex.Replace(Htmlstring, @"<p>", "", RegexOptions.IgnoreCase);
271 Htmlstring = Regex.Replace(Htmlstring, @"</p>", "", RegexOptions.IgnoreCase);
272 Htmlstring = Htmlstring.Replace("\r\n", "");
273 Htmlstring = Htmlstring.Replace("\r\n", "");
274 Htmlstring = Htmlstring.Replace(" ", "");
275 return Htmlstring;
276 }
277
278 /// <summary>
279 /// 截取字符串
280 /// </summary>
281 /// <param name="Str"></param>
282 /// <param name="i"></param>
283 /// <param name="Suf"></param>
284 /// <returns></returns>
285 public static string SubStringi(string Str, int i, string Suf = "")
286 {
287 if (Str.Length > i)
288 return Str.Substring(0, i) + Suf;
289 else
290 return Str;
291 }
292
293 /// <summary>
294 /// 去掉最后一个字符
295 /// </summary>
296 /// <param name="str"></param>
297 /// <returns></returns>
298 public static string RemoveLastChar(string str)
299 {
300 if (str.Length > 0)
301 return str.Substring(0, str.Length - 1);
302 else
303 return str;
304 }
305
306 /// <summary>
307 /// 每隔n个字符插入一个字符
308 /// </summary>
309 /// <param name="input">源字符串</param>
310 /// <param name="interval">间隔字符数</param>
311 /// <param name="value">待插入值</param>
312 /// <returns>返回新生成字符串</returns>
313 public static string InsertFormat(string input, int interval, string value)
314 {
315 for (int i = interval; i < input.Length; i += interval + 1)
316 input = input.Insert(i, value);
317 return input;
318 }
319
320 /// <summary>
321 /// 字节转文件单位
322 /// </summary>
323 /// <param name="size"></param>
324 /// <returns></returns>
325 private static string HumanReadableFilesize(double size)
326 {
327 String[] units = new String[] { "B", "KB", "MB", "GB", "TB", "PB" };
328 double mod = 1024.0;
329 int i = 0;
330 while (size >= mod)
331 {
332 size /= mod;
333 i++;
334 }
335 return Math.Round(size) + units[i];
336 }
337
338 /// <summary>
339 /// 检测端口号是否被占用
340 /// </summary>
341 /// <param name="port">端口号</param>
342 /// <returns>True:被占用 False:没被占用</returns>
343 public static bool portInUse(int port)
344 {
345 bool inUse = false;
346 IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
347 IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();
348 foreach (IPEndPoint endPoint in ipEndPoints)
349 {
350 if (endPoint.Port == port)
351 {
352 inUse = true;
353 break;
354 }
355 }
356 return inUse;
357 }
358
359 /// <summary>
360 /// 获取本机IP地址
361 /// </summary>
362 /// <returns>本机IP地址</returns>
363 public static string getLocalhostIP()
364 {
365 //IPHostEntry ihe = Dns.GetHostEntry(Dns.GetHostName());
366 //IPAddress myIvp6 = ihe.AddressList[1];
367 //IPAddress myIp4 = ihe.AddressList[3];
368 //return myIp4.ToString();
369
370 IPHostEntry ihe = Dns.GetHostByName(Dns.GetHostName());
371 IPAddress myIp = ihe.AddressList[0];
372 return myIp.ToString();
373 }
374
375 /// <summary>
376 /// 反转字符串
377 /// </summary>
378 /// <param name="str"></param>
379 /// <returns></returns>
380 public static string transition(string str)
381 {
382 char[] c = str.ToCharArray();
383 string value = string.Empty;
384 for (int i = 0; i < c.Length; i++)
385 {
386 value += c[c.Length - 1 - i].ToString();
387 }
388 return value;
389 }
390
391 /// <summary>
392 /// 获取指定目录下的文件
393 /// </summary>
394 /// <param name="folderName">要获取的文件夹</param>
395 /// <param name="fileFilter">后缀筛选 *.html</param>
396 /// <param name="isContainSubFolder">是否遍历子文件夹</param>
397 /// <returns></returns>
398 public static ArrayList GetAllFilesByFolder(string folderName, string fileFilter, bool isContainSubFolder)
399 {
400 ArrayList resArray = new ArrayList();
401 string[] files = Directory.GetFiles(folderName, fileFilter);
402 for (int i = 0; i < files.Length; i++)
403 {
404 resArray.Add(files[i]);
405 }
406 if (isContainSubFolder)
407 {
408 string[] folders = Directory.GetDirectories(folderName);
409 for (int j = 0; j < folders.Length; j++)
410 {
411 //遍历所有文件夹
412 ArrayList temp = GetAllFilesByFolder(folders[j], fileFilter, isContainSubFolder);
413 resArray.AddRange(temp);
414 }
415 }
416 return resArray;
417 }
418
419 public static void LoadHeadPhoto(string DownPath, string WebFilePath)
420 {
421 WebClient webClient = null;
422 FileStream fileStream = null;
423 try
424 {
425 string GrayPath = string.Empty;
426 string[] GrayPaths = DownPath.Split('.');
427 GrayPaths[GrayPaths.Length - 1] = "Gray." + GrayPaths[GrayPaths.Length - 1];
428 for (int i = 0; i < GrayPaths.Length; i++)
429 {
430 GrayPath += GrayPaths[i];
431 if (i != GrayPaths.Length - 1)
432 {
433 GrayPath += ".";
434 }
435 }
436 webClient = new WebClient();
437
438 if (File.Exists(DownPath))
439 {
440 File.Delete(DownPath);
441 }
442 if (File.Exists(GrayPath))
443 {
444 File.Delete(GrayPath);
445 }
446 webClient.DownloadFile(new Uri(WebFilePath), DownPath);
447
448 BitmapImage bitmapImage = new BitmapImage(new Uri(DownPath));
449 FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();
450 newFormatedBitmapSource.BeginInit();
451 newFormatedBitmapSource.Source = bitmapImage;
452 newFormatedBitmapSource.DestinationFormat = PixelFormats.Gray8;
453 newFormatedBitmapSource.EndInit();
454
455 JpegBitmapEncoder encoder = new JpegBitmapEncoder();
456 encoder.Frames.Add(BitmapFrame.Create(newFormatedBitmapSource));
457 fileStream = new FileStream(GrayPath, FileMode.Create, FileAccess.ReadWrite);
458 encoder.Save(fileStream);
459 }
460 catch (System.IO.IOException) { }
461 catch (Exception)
462 {
463 }
464 finally
465 {
466 try
467 {
468 if (webClient != null)
469 webClient.Dispose();
470 if (fileStream != null)
471 fileStream.Close();
472 GC.Collect();
473 }
474 catch (Exception ex) { LoggerHandler.HandleException(ex); }
475 }
476 }
477 /// <summary>
478 /// 测试延迟 ping
479 /// </summary>
480 /// <param name="ip"></param>
481 /// <returns></returns>
482 public static long getDelay(string ip)
483 {
484 long v = 0;
485 try
486 {
487 //远程服务器IP
488 string ipStr = ip;
489 //构造Ping实例
490 Ping pingSender = new Ping();
491 //Ping 选项设置
492 PingOptions options = new PingOptions();
493 options.DontFragment = true;
494 //测试数据
495 string data = "getDelay";
496 byte[] buffer = Encoding.ASCII.GetBytes(data);
497 //设置超时时间
498 int timeout = 1000;
499 //调用同步 send 方法发送数据,将返回结果保存至PingReply实例
500 PingReply reply = pingSender.Send(ipStr, timeout, buffer, options);
501 v = reply.Status == IPStatus.Success ? reply.RoundtripTime : -1;
502 }
503 catch (Exception)
504 {
505 v = -1;
506 }
507 if (eventPing != null)
508 eventPing(v, null);
509 return v;
510 }
511 }
512 }