CustomPublicMethod.cs 113 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Drawing;
  5. using System.ComponentModel; // 先添加该引用
  6. using System.IO;
  7. using System.Linq;
  8. using System.Drawing.Imaging;
  9. using System.Security.Cryptography.X509Certificates;
  10. using System.Net.Security;
  11. using System.Collections.Specialized;
  12. using System.Net;
  13. using Biff8Excel;
  14. using System.Runtime.Serialization.Json;
  15. namespace LYFZ.WinAPI
  16. {
  17. /// <summary>
  18. /// 自定义公共方法
  19. /// </summary>
  20. public class CustomPublicMethod
  21. {
  22. /// <summary>
  23. /// WebForm和WinForm通用的取当前根目录的方法
  24. /// </summary>
  25. public static string BasePath
  26. {
  27. get
  28. {
  29. System.Diagnostics.Process p = System.Diagnostics.Process.GetCurrentProcess();
  30. //WebDev.WebServer visual studio web server
  31. //xxx.vhost Winform
  32. //w3wp IIS7
  33. //aspnet_wp IIS6
  34. string processName = p.ProcessName.ToLower();
  35. string retPath = System.Windows.Forms.Application.StartupPath;
  36. if (processName == "aspnet_wp" || processName == "w3wp" || processName == "webdev.webserver" || processName == "iisexpress")
  37. {
  38. if (System.Web.HttpContext.Current != null)
  39. retPath = System.Web.HttpContext.Current.Server.MapPath("~/").TrimEnd(new char[] { '\\' });
  40. else //当控件在定时器的触发程序中使用时就为空
  41. {
  42. retPath = System.AppDomain.CurrentDomain.BaseDirectory.TrimEnd(new char[] { '\\' });
  43. }
  44. }
  45. return retPath;
  46. }
  47. }
  48. /// <summary>
  49. /// 转 20161003160647 (yyyyMMddHHmmss)格式long为时间类型
  50. /// </summary>
  51. /// <param name="dtString">20161003160647 (yyyyMMddHHmmss)格式long</param>
  52. /// <returns></returns>
  53. public static DateTime StringToDateTime(long dtLong)
  54. {
  55. return StringToDateTime(dtLong.ToString());
  56. }
  57. /// <summary>
  58. /// 转 20161003160647(yyyyMMddHHmmss) 格式字符串为时间类型
  59. /// </summary>
  60. /// <param name="dtString">20161003160647 (yyyyMMddHHmmss)格式字符串</param>
  61. /// <returns></returns>
  62. public static DateTime StringToDateTime(string dtString)
  63. {
  64. return Convert.ToDateTime(dtString.Insert(4, "-").Insert(7, "-").Insert(10, " ").Insert(13, ":").Insert(16, ":"));
  65. }
  66. /// <summary>
  67. /// 转DateTime 为 yyyyMMddHHmmss 格式的 long
  68. /// </summary>
  69. /// <param name="t"></param>
  70. /// <returns></returns>
  71. public static long DateTimeToLong(DateTime t)
  72. {
  73. return Convert.ToInt64(t.ToString("yyyyMMddHHmmss"));
  74. }
  75. /// <summary>
  76. /// 转Long格式:标准时间从1970年到现在的毫秒数
  77. /// </summary>
  78. /// <param name="dt"></param>
  79. /// <returns></returns>
  80. public static long ConvertDataTimeLong(DateTime dt)
  81. {
  82. DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  83. TimeSpan toNow = dt.Subtract(dtStart);
  84. long timeStamp = toNow.Ticks;
  85. timeStamp = long.Parse(timeStamp.ToString().Substring(0, timeStamp.ToString().Length - 4));
  86. return timeStamp;
  87. }
  88. /// <summary>
  89. /// 转标准时间从1970年到现在的毫秒数 Long格式 为 DateTime
  90. /// </summary>
  91. /// <param name="d"></param>
  92. /// <returns></returns>
  93. public static DateTime ConvertLongDateTime(long d)
  94. {
  95. DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  96. long lTime = long.Parse(d + "0000");
  97. TimeSpan toNow = new TimeSpan(lTime);
  98. DateTime dtResult = dtStart.Add(toNow);
  99. return dtResult;
  100. }
  101. static string _SpecialCharacters = "\\/:*?\"<>|";
  102. /// <summary>
  103. /// 特殊字符
  104. /// </summary>
  105. public static string SpecialCharacters
  106. {
  107. get { return CustomPublicMethod._SpecialCharacters; }
  108. }
  109. /// <summary>
  110. /// 检查指定字符串中是否存在特殊字符
  111. /// </summary>
  112. /// <param name="str"></param>
  113. /// <returns></returns>
  114. public static bool IsSpecialCharacters(string str)
  115. {
  116. bool bl = false;
  117. char[] tempChars = str.ToCharArray();
  118. for (int i = 0; i < tempChars.Length; i++)
  119. {
  120. if (_SpecialCharacters.Contains(tempChars[i]))
  121. {
  122. bl = true;
  123. break;
  124. }
  125. }
  126. return bl;
  127. }
  128. /// <summary>
  129. /// 转换(过滤)特殊字符
  130. /// </summary>
  131. /// <param name="str"></param>
  132. /// <returns></returns>
  133. public static string ConvertSpecialCharacter(string str)
  134. {
  135. return str.Replace(':', ':')
  136. .Replace('?', '?')
  137. .Replace('|', '|')
  138. .Replace('>', '>')
  139. .Replace('*', 'x')
  140. .Replace("\r", "")
  141. .Replace("\n", "")
  142. .Replace("\t", "");
  143. }
  144. /// <summary>
  145. /// 时间戳转为C#格式时间
  146. /// </summary>
  147. /// <param name="timeStamp"></param>
  148. /// <returns></returns>
  149. public static DateTime StampToDateTime(string timeStamp)
  150. {
  151. DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  152. long lTime = long.Parse(timeStamp + "0000000");
  153. TimeSpan toNow = new TimeSpan(lTime);
  154. return dateTimeStart.Add(toNow);
  155. }
  156. /// <summary>
  157. /// DateTime时间格式转换为Unix时间戳格式
  158. /// </summary>
  159. /// <param name="time"></param>
  160. /// <returns></returns>
  161. public static int DateTimeToStamp(System.DateTime time)
  162. {
  163. System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
  164. return (int)(time - startTime).TotalSeconds;
  165. }
  166. /// <summary>
  167. /// 判断路径文件名指定的文件是否为 常用图片格式 jpg、jpge、png、bmp、tag、gif、
  168. /// </summary>
  169. /// <param name="fileName">路径文件名</param>
  170. /// <returns></returns>
  171. public static bool ExistsImgage(string fileName)
  172. {
  173. if (System.IO.Path.GetExtension(fileName).ToLower() == ".jpg".ToLower()
  174. || System.IO.Path.GetExtension(fileName).ToLower() == ".jpge"
  175. || System.IO.Path.GetExtension(fileName).ToLower() == ".png"
  176. || System.IO.Path.GetExtension(fileName).ToLower() == ".bmp"
  177. || System.IO.Path.GetExtension(fileName).ToLower() == ".tag"
  178. || System.IO.Path.GetExtension(fileName).ToLower() == ".gif")
  179. {
  180. return true;
  181. }
  182. else
  183. {
  184. return false;
  185. }
  186. }
  187. /// <summary>
  188. /// C++ Dll 获取指定图片信息
  189. /// </summary>
  190. /// <param name="lpImgPath">要获取的指定的图片信息</param>
  191. /// <param name="dwWidth">ref 宽</param>
  192. /// <param name="dwHeight">ref 高</param>
  193. /// <param name="fHorizontal">ref 水平方向分辨率</param>
  194. /// <param name="fVertical">ref 垂直方向分辨率</param>
  195. /// <returns></returns>
  196. public static bool GetImgInfo(string lpImgPath, ref int dwWidth, ref int dwHeight, ref float fHorizontal, ref float fVertical)
  197. {
  198. try
  199. {
  200. bool ret = false;
  201. uint w = 0;
  202. uint h = 0;
  203. if (Environment.Is64BitProcess)
  204. {
  205. //64-bit
  206. ret = Win_X64.GetImgInfo(lpImgPath, ref w, ref h, ref fHorizontal, ref fVertical);
  207. }
  208. else
  209. {
  210. //估计很长一段时间内都是32-bit
  211. ret = Win_X86.GetImgInfo(lpImgPath, ref w, ref h, ref fHorizontal, ref fVertical);
  212. }
  213. dwWidth = Convert.ToInt32(w);
  214. dwHeight = Convert.ToInt32(h);
  215. return ret;
  216. }
  217. catch
  218. {
  219. return false;
  220. }
  221. }
  222. /// <summary>
  223. /// C++ Dll 生成缩略图
  224. /// </summary>
  225. /// <param name="lpImgPath">要生成的原图路径</param>
  226. /// <param name="lpNewImgPath">生成的缩略图要保存的路径</param>
  227. /// <param name="dwWidth">缩略图宽</param>
  228. /// <param name="dwHeight">缩略图高</param>
  229. /// <param name="dwQuality">0~100 品质 如果为 0 时无法控件品质 但可以使32位系统生成百兆以后相片的缩略图</param>
  230. /// <param name="isFullCut"> 是否为完整模式,按指定高宽增加画布空白或裁减尽可能的显示出最完整原图(不变形)</param>
  231. /// <returns></returns>
  232. public static bool GenerationImageThumbnail(string lpImgPath, string lpNewImgPath, int dwWidth, int dwHeight, int dwQuality, bool isFullCut = false)
  233. {
  234. try
  235. {
  236. bool ret = false;
  237. if (Environment.Is64BitProcess)
  238. {
  239. //64-bit
  240. ret = Win_X64.GenerationThumbnail(lpImgPath, lpNewImgPath, (uint)dwWidth, (uint)dwHeight, (uint)dwQuality);
  241. if (!ret)
  242. {
  243. ret = Win_X64.GenerationThumbnail(lpImgPath, lpNewImgPath, (uint)dwWidth, (uint)dwHeight, 0);
  244. }
  245. }
  246. else
  247. {
  248. //估计很长一段时间内都是32-bit
  249. ret = Win_X86.GenerationThumbnail(lpImgPath, lpNewImgPath, (uint)dwWidth, (uint)dwHeight, (uint)dwQuality);
  250. if (!ret)
  251. {
  252. ret = Win_X86.GenerationThumbnail(lpImgPath, lpNewImgPath, (uint)dwWidth, (uint)dwHeight, 0);
  253. }
  254. }
  255. if (ret && isFullCut)
  256. {
  257. Image image = Image.FromFile(lpNewImgPath);
  258. Bitmap result = new Bitmap(dwWidth, dwHeight);
  259. using (Graphics g = Graphics.FromImage(result))
  260. {
  261. Brush brush = Brushes.White;
  262. g.FillRectangle(brush, new Rectangle(new Point(0, 0), result.Size));
  263. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  264. g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  265. g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
  266. g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
  267. g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
  268. g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
  269. g.Clear(Color.Transparent);
  270. //对齐方式
  271. RectangleF destRect = new RectangleF(new PointF(-(float)((image.Size.Width - result.Size.Width) * 0.5), -(float)((image.Size.Height - result.Size.Height) * 0.5)), image.Size);
  272. g.DrawImage(image, destRect, new RectangleF(new PointF(0F, 0F), image.Size), GraphicsUnit.Pixel);
  273. image.Dispose();
  274. image = null;
  275. }
  276. SaveIamge(result, 95, lpNewImgPath);
  277. }
  278. return ret;
  279. }
  280. catch
  281. {
  282. return false;
  283. }
  284. }
  285. /// <summary>
  286. /// 保存图片。
  287. /// </summary>
  288. /// <param name="image">要保存的图片</param>
  289. /// <param name="quality">品质(1L~100L之间,数值越大品质越好)</param>
  290. /// <param name="filename">保存路径</param>
  291. public static void SaveIamge(Bitmap image, long quality, string filename)
  292. {
  293. using (EncoderParameters encoderParams = new EncoderParameters(1))
  294. {
  295. using (EncoderParameter parameter = (encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality)))
  296. {
  297. ImageCodecInfo encoder = null;
  298. //取得扩展名
  299. string ext = Path.GetExtension(filename);
  300. if (string.IsNullOrEmpty(ext))
  301. ext = ".jpg";
  302. //根据扩展名得到解码、编码器
  303. foreach (ImageCodecInfo codecInfo in ImageCodecInfo.GetImageEncoders())
  304. {
  305. if (System.Text.RegularExpressions.Regex.IsMatch(codecInfo.FilenameExtension, string.Format(@"(;|^)\*\{0}(;|$)", ext), System.Text.RegularExpressions.RegexOptions.IgnoreCase))
  306. {
  307. encoder = codecInfo;
  308. break;
  309. }
  310. }
  311. string dirPath = Path.GetDirectoryName(filename);
  312. if (!Directory.Exists(dirPath))
  313. {
  314. Directory.CreateDirectory(dirPath);
  315. }
  316. if (System.IO.File.Exists(filename))
  317. {
  318. System.IO.File.Delete(filename);
  319. }
  320. image.Save(filename, encoder, encoderParams);
  321. image.Dispose();
  322. }
  323. }
  324. }
  325. /// <summary>
  326. /// 检查指定打印机名是否为有效的打印机
  327. /// </summary>
  328. /// <param name="printerName"></param>
  329. /// <returns></returns>
  330. public static bool CheckValidPrinter(string printerName)
  331. {
  332. System.Drawing.Printing.PrinterSettings myPrinter = new System.Drawing.Printing.PrinterSettings();
  333. myPrinter.PrinterName = printerName;//@"\\LIUCHAO-PC\Foxit Reader PDF Printer";
  334. return myPrinter.IsValid;
  335. }
  336. /// <summary>
  337. /// 程序执行时间测试
  338. /// </summary>
  339. /// <param name="dateBegin">开始时间</param>
  340. /// <param name="dateEnd">结束时间</param>
  341. /// <returns>返回(秒)单位,比如: 0.00239秒</returns>
  342. public static double ExecDateDiff(DateTime dateBegin, DateTime dateEnd)
  343. {
  344. TimeSpan ts1 = new TimeSpan(dateBegin.Ticks);
  345. TimeSpan ts2 = new TimeSpan(dateEnd.Ticks);
  346. TimeSpan ts3 = ts1.Subtract(ts2).Duration();
  347. //你想转的格式
  348. return ts3.TotalMilliseconds;
  349. }
  350. /// <summary>
  351. /// 释放并清除指定控件中的所以子控件
  352. /// </summary>
  353. /// <param name="_Control"></param>
  354. public static void DisposeControls(System.Windows.Forms.Control _Control)
  355. {
  356. try
  357. {
  358. foreach (System.Windows.Forms.Control c in _Control.Controls)
  359. {
  360. if (c.Controls.Count > 0)
  361. {
  362. DisposeControls(c);
  363. c.Controls.Clear();
  364. }
  365. c.Dispose();
  366. }
  367. _Control.Controls.Clear();
  368. }
  369. catch { }
  370. }
  371. /// <summary>
  372. /// 移除特殊符号
  373. /// </summary>
  374. /// <param name="fileName"></param>
  375. /// <returns></returns>
  376. public static string RemoveSpecialSymbol(string fileName)
  377. {
  378. return fileName.Replace(";", "");
  379. }
  380. /// <summary>
  381. /// 判断是否是IP地址格式 0.0.0.0
  382. /// </summary>
  383. /// <param name="str1">待判断的IP地址</param>
  384. /// <returns>true or false</returns>
  385. public static bool IsIPAddress(string str1)
  386. {
  387. if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;
  388. string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";
  389. System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(regformat, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  390. return regex.IsMatch(str1);
  391. }
  392. /// <summary>
  393. /// 检查指定网络地址是否为内网地址
  394. /// </summary>
  395. /// <param name="networkAddress"></param>
  396. /// <returns></returns>
  397. public static bool CheckInternaNetworkAddress(string networkAddress)
  398. {
  399. bool ret = false;
  400. if (IsInnerIP(networkAddress) || networkAddress.Split('.').Length < 3)
  401. {
  402. ret = true;
  403. }
  404. return ret;
  405. }
  406. /// <summary>
  407. /// 判断IP地址是否为内网IP地址
  408. /// </summary>
  409. /// <param name="ipAddress">IP地址字符串</param>
  410. /// <returns></returns>
  411. public static bool IsInnerIP(string ipAddress)
  412. {
  413. bool isInnerIp = false;
  414. long ipNum = GetIpNum(ipAddress);
  415. /**
  416. 私有IP:A类 10.0.0.0-10.255.255.255
  417. B类 172.16.0.0-172.31.255.255
  418. C类 192.168.0.0-192.168.255.255
  419. 当然,还有127这个网段是环回地址
  420. **/
  421. long aBegin = GetIpNum("10.0.0.0");
  422. long aEnd = GetIpNum("10.255.255.255");
  423. long bBegin = GetIpNum("172.16.0.0");
  424. long bEnd = GetIpNum("172.31.255.255");
  425. long cBegin = GetIpNum("192.168.0.0");
  426. long cEnd = GetIpNum("192.168.255.255");
  427. isInnerIp = IsInner(ipNum, aBegin, aEnd) || IsInner(ipNum, bBegin, bEnd) || IsInner(ipNum, cBegin, cEnd) || ipAddress.Equals("127.0.0.1");
  428. return isInnerIp;
  429. }
  430. /// <summary>
  431. /// 把IP地址转换为Long型数字
  432. /// </summary>
  433. /// <param name="ipAddress">IP地址字符串</param>
  434. /// <returns></returns>
  435. public static long GetIpNum(string ipAddress)
  436. {
  437. try
  438. {
  439. String[] ip = ipAddress.Split('.');
  440. long a = int.Parse(ip[0]);
  441. long b = int.Parse(ip[1]);
  442. long c = int.Parse(ip[2]);
  443. long d = int.Parse(ip[3]);
  444. long ipNum = a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
  445. return ipNum;
  446. }
  447. catch
  448. {
  449. return 0;
  450. }
  451. }
  452. /// <summary>
  453. /// 判断用户IP地址转换为Long型后是否在内网IP地址所在范围
  454. /// </summary>
  455. /// <param name="userIp"></param>
  456. /// <param name="begin"></param>
  457. /// <param name="end"></param>
  458. /// <returns></returns>
  459. public static bool IsInner(long userIp, long begin, long end)
  460. {
  461. return (userIp >= begin) && (userIp <= end);
  462. }
  463. /// <summary>
  464. /// 全局ID GUID获取19位的唯一数字序列
  465. /// </summary>
  466. /// <returns></returns>
  467. public static long GenerateId()
  468. {
  469. byte[] buffer = Guid.NewGuid().ToByteArray();
  470. return BitConverter.ToInt64(buffer, 0);
  471. }
  472. /// <summary>
  473. /// 根据GUID获取32位的唯一字符串
  474. /// </summary>
  475. /// <param name=\"guid\"></param>
  476. /// <returns></returns>
  477. public static string GuidTo32String()
  478. {
  479. return Guid.NewGuid().ToString("n").ToUpper();
  480. }
  481. /// <summary>
  482. /// 根据GUID获取16位的唯一字符串
  483. /// </summary>
  484. /// <param name=\"guid\"></param>
  485. /// <returns></returns>
  486. public static string GuidTo16String()
  487. {
  488. long i = 1;
  489. foreach (byte b in Guid.NewGuid().ToByteArray())
  490. i *= ((int)b + 1);
  491. return string.Format("{0:x}", i - DateTime.Now.Ticks);
  492. }
  493. /// <summary>
  494. /// 生成22位唯一的数字 并发可用
  495. /// </summary>
  496. /// <returns></returns>
  497. public static string GenerateUniqueID()
  498. {
  499. System.Threading.Thread.Sleep(1); //保证yyyyMMddHHmmssffff唯一
  500. Random d = new Random(BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0));
  501. string strUnique = DateTime.Now.ToString("yyyyMMddHHmmssffff") + d.Next(1000, 9999);
  502. return strUnique;
  503. }
  504. //端口号的范围从0到65535
  505. /// <summary>
  506. /// 获取指定范围的随机端口号
  507. /// </summary>
  508. /// <param name="start">开始值</param>
  509. /// <param name="end">结束值</param>
  510. /// <returns></returns>
  511. public static int GetRandomPortNumber(int start = 0, int end = 65535)
  512. {
  513. if (start <= 0)
  514. {
  515. start = 0;
  516. }
  517. if (start > 65534)
  518. {
  519. start = 65534;
  520. }
  521. if (end <= 1)
  522. {
  523. end = 1;
  524. }
  525. if (end > 65535)
  526. {
  527. end = 65535;
  528. }
  529. return new Random().Next(start, end);
  530. }
  531. /// <summary>
  532. /// 26个大写英文字母
  533. /// </summary>
  534. public static char[] CharArray = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
  535. /// <summary>
  536. /// 获取指定长度的随机字符串
  537. /// </summary>
  538. /// <param name="length">指定长度 最大长度为 64 个字符</param>
  539. /// <param name="isSpecialChar">是否含有特殊字符</param>
  540. /// <returns></returns>
  541. public static string GetSpecifyLengthRandomString(int length = 12, bool isSpecialChar = false)
  542. {
  543. if (length > 64)
  544. {
  545. length = 64;
  546. }
  547. Random ran = new Random();
  548. int RandKey = ran.Next(0, 25);
  549. string retString = CharArray[RandKey] + LYFZ.WinAPI.SDKSecurity.Encode(LYFZ.WinAPI.CustomPublicMethod.GenerateId().ToString()
  550. + LYFZ.WinAPI.CustomPublicMethod.GenerateId().ToString() + LYFZ.WinAPI.CustomPublicMethod.GenerateId().ToString());
  551. if (isSpecialChar)
  552. {
  553. retString = retString.Replace("==", "#Z").Replace("=", "&A").Replace("/", "@T").Replace("+", "&K");
  554. retString = retString.Insert(ran.Next(1, 10), "@");
  555. retString = retString.Insert(ran.Next(11, 20), "&");
  556. retString = retString.Insert(ran.Next(21, 32), "#");
  557. }
  558. else
  559. {
  560. retString = retString.Replace("==", "AZ").Replace("=", "A").Replace("/", "T").Replace("+", "K");
  561. }
  562. return retString.Substring(0, length);
  563. }
  564. /// <summary>
  565. /// 打开指定目录或文件
  566. /// </summary>
  567. /// <param name="arguments"></param>
  568. public static void OpenDirectory(string arguments)
  569. {
  570. if (System.IO.Directory.Exists(arguments))
  571. {
  572. System.Diagnostics.Process.Start(arguments);
  573. }
  574. else
  575. {
  576. LYFZ.WinAPI.CustomPublicMethod.RunStart("Explorer.exe", arguments);
  577. }
  578. }
  579. /// <summary>
  580. /// 运行外部应用程序
  581. /// </summary>
  582. /// <param name="path"></param>
  583. public static void RunStart(string path)
  584. {
  585. LYFZ.WinAPI.CustomPublicMethod.RunStart(path, "");
  586. }
  587. /// <summary>
  588. /// 运行外部应用程序
  589. /// </summary>
  590. /// <param name="path"></param>
  591. public static void RunStart(string path, string arguments = "")
  592. {
  593. try
  594. {
  595. if (System.IO.File.Exists(LYFZ.WinAPI.CustomPublicMethod.BasePath + path))
  596. {
  597. System.Diagnostics.Process.Start(LYFZ.WinAPI.CustomPublicMethod.BasePath + path, arguments);
  598. }
  599. else
  600. {
  601. System.Diagnostics.Process.Start(path, arguments);
  602. }
  603. }
  604. catch
  605. {
  606. }
  607. }
  608. /// <summary>
  609. ///
  610. /// </summary>
  611. /// <param name="dirPath"></param>
  612. /// <returns></returns>
  613. public static long GetDirectoryLength(string dirPath)
  614. {
  615. //判断给定的路径是否存在,如果不存在则退出
  616. if (!Directory.Exists(dirPath))
  617. return 0;
  618. long len = 0;
  619. //定义一个DirectoryInfo对象
  620. DirectoryInfo di = new DirectoryInfo(dirPath);
  621. //通过GetFiles方法,获取di目录中的所有文件的大小
  622. foreach (FileInfo fi in di.GetFiles())
  623. {
  624. len += fi.Length;
  625. }
  626. //获取di中所有的文件夹,并存到一个新的对象数组中,以进行递归
  627. DirectoryInfo[] dis = di.GetDirectories();
  628. if (dis.Length > 0)
  629. {
  630. for (int i = 0; i < dis.Length; i++)
  631. {
  632. len += GetDirectoryLength(dis[i].FullName);
  633. }
  634. }
  635. return len;
  636. }
  637. /// <summary>
  638. /// 获取文件夹中所有文件大小 单位 MB
  639. /// </summary>
  640. /// <param name="filePath"></param>
  641. /// <returns></returns>
  642. public static long GetMBDirectorySize(string dirPath)
  643. {
  644. return GetDirectoryLength(dirPath) / 1024 / 1024;
  645. }
  646. /// <summary>
  647. /// 获取文件集合中所有文件大小 单位 MB
  648. /// </summary>
  649. /// <param name="filePath"></param>
  650. /// <returns></returns>
  651. public static long GetMBFilesSize(string[] filesPaths)
  652. {
  653. long tempSize = 0;
  654. foreach (string filePath in filesPaths)
  655. {
  656. FileInfo fileInfo = new FileInfo(filePath);
  657. tempSize += fileInfo.Length;
  658. }
  659. return tempSize / 1024 / 1024;
  660. }
  661. /// <summary>
  662. /// 也是利用递归的思想,只不过是通过File类的Exits方法来判断
  663. /// 所给路径中所对应的是否为文件
  664. /// </summary>
  665. /// <param name="filePath"></param>
  666. /// <returns></returns>
  667. public static long FileSize(string filePath)
  668. {
  669. long temp = 0;
  670. //判断当前路径所指向的是否为文件
  671. if (File.Exists(filePath) == false)
  672. {
  673. string[] str1 = Directory.GetFileSystemEntries(filePath);
  674. foreach (string s1 in str1)
  675. {
  676. temp += FileSize(s1);
  677. }
  678. }
  679. else
  680. {
  681. //定义一个FileInfo对象,使之与filePath所指向的文件向关联,
  682. //以获取其大小
  683. FileInfo fileInfo = new FileInfo(filePath);
  684. return fileInfo.Length;
  685. }
  686. return temp;
  687. }
  688. /// <summary>
  689. /// 返回中文的星期几
  690. /// </summary>
  691. /// <param name="dayOfWeek"></param>
  692. /// <returns></returns>
  693. public static string GetDayOfWeek(DayOfWeek dayOfWeek)
  694. {
  695. string str = "";
  696. switch (dayOfWeek)
  697. {
  698. case DayOfWeek.Sunday: str = "星期日"; break;
  699. case DayOfWeek.Monday: str = "星期一"; break;
  700. case DayOfWeek.Tuesday: str = "星期二"; break;
  701. case DayOfWeek.Wednesday: str = "星期三"; break;
  702. case DayOfWeek.Thursday: str = "星期四"; break;
  703. case DayOfWeek.Friday: str = "星期五"; break;
  704. case DayOfWeek.Saturday: str = "星期六"; break;
  705. }
  706. return str;
  707. }
  708. /// <summary>
  709. /// 根据路径获取图片
  710. /// </summary>
  711. /// <param name="imgaPath">程序运行当前根目录下的Resources资源文件夹路径 如:\\ToolsMenu\\payments.png</param>
  712. /// <returns></returns>
  713. public static System.Drawing.Image GetMenuItemImage(string imgaPath)
  714. {
  715. System.Drawing.Image retimage = null;
  716. if (imgaPath != "")
  717. {
  718. try
  719. {
  720. string tempPath = CustomPublicMethod.BasePath + "\\Resources" + imgaPath;
  721. // System.Drawing.Image image = new System.Drawing.Bitmap(tempPath);
  722. retimage = (System.Drawing.Image)GetPathToBitmap(tempPath);
  723. // image.Dispose();
  724. }
  725. catch
  726. {
  727. }
  728. }
  729. return retimage;
  730. }
  731. /// <summary>
  732. /// 根据路径获取图片
  733. /// </summary>
  734. /// <param name="imgaPath"></param>
  735. /// <returns></returns>
  736. public static System.Drawing.Bitmap GetPathToBitmap(string imgaPath)
  737. {
  738. try
  739. {
  740. FileStream fs = new FileStream(imgaPath, FileMode.Open, FileAccess.Read);
  741. Bitmap bmp = new Bitmap(fs);
  742. Bitmap retbmp = new Bitmap(bmp);
  743. fs.Close();
  744. fs.Dispose();
  745. bmp.Dispose();
  746. bmp = null;
  747. return retbmp;
  748. }
  749. catch { return null; }
  750. }
  751. #region 获取灰色图像
  752. /// <summary>
  753. /// 获取灰色图像
  754. /// </summary>
  755. /// <returns></returns>
  756. public static Image GetGrayImage(Image image)
  757. {
  758. return CustomPublicMethod.GetGrayImage(new Bitmap(image));
  759. }
  760. /// <summary>
  761. /// 获取灰色图像
  762. /// </summary>
  763. /// <returns></returns>
  764. public static Bitmap GetGrayImage(Bitmap image)
  765. {
  766. int Height = image.Height;
  767. int Width = image.Width;
  768. Bitmap bitmap = image;
  769. Bitmap MyBitmap = new Bitmap(image);
  770. //使用左上角的一点的颜色作为我们透明色
  771. Color colorTransparent = MyBitmap.GetPixel(0, 0);
  772. Color pixel;
  773. for (int x = 0; x < Width; x++)
  774. {
  775. for (int y = 0; y < Height; y++)
  776. {
  777. pixel = MyBitmap.GetPixel(x, y);
  778. if (pixel != colorTransparent)
  779. {
  780. int r, g, b, Result = 0;
  781. r = pixel.R;
  782. g = pixel.G;
  783. b = pixel.B;
  784. //实例程序以加权平均值法产生黑白图像
  785. int iType = 2;
  786. switch (iType)
  787. {
  788. case 0://平均值法
  789. Result = ((r + g + b) / 3);
  790. break;
  791. case 1://最大值法
  792. Result = r > g ? r : g;
  793. Result = Result > b ? Result : b;
  794. break;
  795. case 2://加权平均值法
  796. Result = ((int)(0.7 * r) + (int)(0.2 * g) + (int)(0.1 * b));
  797. break;
  798. }
  799. bitmap.SetPixel(x, y, Color.FromArgb(Result, Result, Result));
  800. }
  801. }
  802. }
  803. MyBitmap.Dispose();
  804. return bitmap;
  805. }
  806. #endregion
  807. /// <summary>
  808. /// 返回指定类型是否为允许为null的 Nullable泛型对象
  809. /// </summary>
  810. /// <param name="_type"></param>
  811. /// <returns>是Nullable泛型对象为 true 否则为 false</returns>
  812. public static bool IsNullable(Type _type)
  813. {
  814. bool bl = _type.Name.ToLower().Contains("Nullable".ToLower());
  815. return bl;
  816. }
  817. /// <summary>
  818. /// 验证一个类的完全限定名中是否以“system.”开头
  819. /// </summary>
  820. /// <param name="classFullName"></param>
  821. /// <returns>以“system.”开头为 true 否则为 false </returns>
  822. public static bool VerificationClassFullNameIsSystem(string classFullName)
  823. {
  824. bool bl = false;
  825. if (classFullName.ToLower().IndexOf("system.") == 0)
  826. {
  827. bl = true;
  828. }
  829. return bl;
  830. }
  831. /// <summary>
  832. /// 获取实例对象属性的值
  833. /// </summary>
  834. /// <param name="model">实例对象</param>
  835. /// <param name="propertyName">属性名</param>
  836. /// <returns></returns>
  837. public static object GetPropertyValue(object model, string propertyName)
  838. {
  839. System.Reflection.PropertyInfo propertyInfo = model.GetType().GetProperty(propertyName);
  840. if (propertyInfo != null)
  841. {
  842. object tempValue = propertyInfo.GetValue(model, null);//对应字段值
  843. return tempValue;
  844. }
  845. else
  846. {
  847. return null;
  848. }
  849. }
  850. /// <summary>
  851. /// 设置实例对象属性的值
  852. /// </summary>
  853. /// <param name="model">实例对象</param>
  854. /// <param name="propertyInfo">属性对象</param>
  855. /// <param name="value">要设置的值</param>
  856. public static void SetPropertyValue(object model, System.Reflection.PropertyInfo propertyInfo, object value)
  857. {
  858. if (propertyInfo == null)
  859. {
  860. return;
  861. }
  862. Type tempType = propertyInfo.PropertyType;
  863. if (IsNullable(tempType))
  864. {
  865. tempType = Nullable.GetUnderlyingType(propertyInfo.PropertyType);
  866. }
  867. object tempValue = value;
  868. if (tempValue == null)
  869. {
  870. try
  871. {
  872. propertyInfo.SetValue(model, null, null);
  873. }
  874. catch { }
  875. }
  876. else
  877. {
  878. switch (tempType.Name)
  879. {
  880. // 空引用。
  881. case "Empty":
  882. propertyInfo.SetValue(model, tempValue.ToString(), null);
  883. break;
  884. // 常规类型,表示不会由另一个 TypeCode 显式表示的任何引用或值类型。
  885. case "Object":
  886. propertyInfo.SetValue(model, tempValue, null);
  887. break;
  888. // 数据库空(列)值。
  889. case "DBNull":
  890. propertyInfo.SetValue(model, null, null);
  891. break;
  892. // 简单类型,表示 true 或 false 的布尔值。
  893. case "Boolean":
  894. try
  895. {
  896. propertyInfo.SetValue(model, Convert.ToBoolean(tempValue), null);
  897. }
  898. catch
  899. {
  900. propertyInfo.SetValue(model, false, null);
  901. }
  902. break;
  903. //字符
  904. case "Char":
  905. propertyInfo.SetValue(model, Convert.ToChar(tempValue), null);
  906. break;
  907. // 整型,表示值介于 -128 到 127 之间的有符号 8 位整数。
  908. case "SByte":
  909. propertyInfo.SetValue(model, Convert.ToSByte(tempValue), null);
  910. break;
  911. // 0 and 255.
  912. case "Byte":
  913. propertyInfo.SetValue(model, Convert.ToByte(tempValue), null);
  914. break;
  915. // 整型,表示值介于 -32768 到 32767 之间的有符号 16 位整数。
  916. case "Int16":
  917. propertyInfo.SetValue(model, Convert.ToInt16(tempValue), null);
  918. break;
  919. // 整型,表示值介于 0 到 65535 之间的无符号 16 位整数。
  920. case "UInt16":
  921. propertyInfo.SetValue(model, Convert.ToUInt16(tempValue), null);
  922. break;
  923. // 整型,表示值介于 -2147483648 到 2147483647 之间的有符号 32 位整数。
  924. case "Int32":
  925. try
  926. {
  927. propertyInfo.SetValue(model, Convert.ToInt32(tempValue), null);
  928. }
  929. catch
  930. {
  931. propertyInfo.SetValue(model, Convert.ToInt32(0), null);
  932. }
  933. break;
  934. // 整型,表示值介于 0 到 4294967295 之间的无符号 32 位整数。
  935. case "UInt32":
  936. propertyInfo.SetValue(model, Convert.ToUInt32(tempValue), null);
  937. break;
  938. // 整型,表示值介于 -9223372036854775808 到 9223372036854775807 之间的有符号 64 位整数。
  939. case "Int64":
  940. propertyInfo.SetValue(model, Convert.ToInt64(tempValue), null);
  941. break;
  942. // 整型,表示值介于 0 到 18446744073709551615 之间的无符号 64 位整数。
  943. case "UInt64":
  944. propertyInfo.SetValue(model, Convert.ToUInt64(tempValue), null);
  945. break;
  946. // 浮点型,表示从大约 1.5 x 10 -45 到 3.4 x 10 38 且精度为 7 位的值。
  947. case "Single":
  948. propertyInfo.SetValue(model, Convert.ToSingle(tempValue), null);
  949. break;
  950. // 浮点型,表示从大约 5.0 x 10 -324 到 1.7 x 10 308 且精度为 15 到 16 位的值。
  951. case "Double":
  952. try
  953. {
  954. propertyInfo.SetValue(model, Convert.ToDouble(tempValue), null);
  955. }
  956. catch
  957. {
  958. propertyInfo.SetValue(model, 0, null);
  959. }
  960. break;
  961. // 简单类型,表示从 1.0 x 10 -28 到大约 7.9 x 10 28 且有效位数为 28 到 29 位的值。
  962. case "Decimal":
  963. propertyInfo.SetValue(model, Convert.ToDecimal(tempValue), null);
  964. break;
  965. // 表示一个日期和时间值的类型。
  966. case "DateTime":
  967. try
  968. {
  969. propertyInfo.SetValue(model, Convert.ToDateTime(tempValue), null);
  970. }
  971. catch
  972. {
  973. // propertyInfo.SetValue(model, Convert.ToDateTime("1753-01-01"), null);
  974. }
  975. break;
  976. // 密封类类型,表示 Unicode 字符串。
  977. case "String":
  978. propertyInfo.SetValue(model, tempValue.ToString(), null);
  979. break;
  980. default:
  981. string classFullName = tempType.ToString();
  982. if (!VerificationClassFullNameIsSystem(classFullName))
  983. {
  984. try
  985. {
  986. Type valueType = tempType.Module.Assembly.GetType(classFullName);
  987. // object obj = Activator.CreateInstance(type, null);
  988. tempValue = Activator.CreateInstance(valueType, new object[] { tempValue.ToString() });
  989. }
  990. catch { }
  991. }
  992. propertyInfo.SetValue(model, tempValue, null);
  993. break;
  994. }
  995. }
  996. }
  997. /// <summary>
  998. /// 设置实例对象属性的值
  999. /// </summary>
  1000. /// <param name="model">实例对象</param>
  1001. /// <param name="propertyName">属性名</param>
  1002. /// <param name="value">要设置的值</param>
  1003. public static void SetPropertyValue(object model, string propertyName, object value)
  1004. {
  1005. // Type tempType = model.GetType().GetProperty(propertyName).PropertyType;
  1006. System.Reflection.PropertyInfo propertyInfo = model.GetType().GetProperty(propertyName);
  1007. if (propertyInfo != null)
  1008. {
  1009. SetPropertyValue(model, propertyInfo, value);
  1010. }
  1011. }
  1012. /// <summary>
  1013. /// 获取枚举描述
  1014. /// </summary>
  1015. /// <param name="e"></param>
  1016. /// <returns></returns>
  1017. public static string ConvertEnumToDescription(object e)
  1018. {
  1019. System.Reflection.FieldInfo EnumInfo = e.GetType().GetField(e.ToString());
  1020. DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])EnumInfo.
  1021. GetCustomAttributes(typeof(DescriptionAttribute), false);
  1022. if (EnumAttributes.Length > 0)
  1023. {
  1024. return EnumAttributes[0].Description;
  1025. }
  1026. return e.ToString();
  1027. }
  1028. /// <summary>
  1029. /// 获取完整的文件夹目录
  1030. /// </summary>
  1031. /// <param name="directoryPath"></param>
  1032. /// <returns></returns>
  1033. public static string GetDirectoryPath(string directoryPath)
  1034. {
  1035. if (directoryPath.LastIndexOf(System.IO.Path.DirectorySeparatorChar) != directoryPath.Length - 1)
  1036. {
  1037. directoryPath = directoryPath + System.IO.Path.DirectorySeparatorChar;
  1038. }
  1039. return directoryPath;
  1040. }
  1041. public static void SetColumnDisplayIndex(int index, string columnDisplayString, System.Windows.Forms.DataGridViewColumnCollection columns)
  1042. {
  1043. if (columnDisplayString.Trim() != "")
  1044. {
  1045. string[] columnDisplays = columnDisplayString.Split('|');
  1046. for (int i = 0; i < columnDisplays.Length; i++)
  1047. {
  1048. string[] columnDisplayValues = columnDisplays[i].Split(':');
  1049. string columnName = columnDisplayValues[0];
  1050. int displayIndex = 0;
  1051. try
  1052. {
  1053. displayIndex = Convert.ToInt32(columnDisplayValues[1]);
  1054. }
  1055. catch { }
  1056. bool isDisplay = true;
  1057. try
  1058. {
  1059. isDisplay = Convert.ToBoolean(columnDisplayValues[2]);
  1060. }
  1061. catch { }
  1062. int columnWidth = 100;
  1063. try
  1064. {
  1065. columnWidth = Convert.ToInt32(columnDisplayValues[3]);
  1066. }
  1067. catch { }
  1068. if (displayIndex == index)
  1069. {
  1070. try
  1071. {
  1072. System.Windows.Forms.DataGridViewColumn column = columns[columnName];
  1073. column.DisplayIndex = displayIndex;
  1074. column.Width = columnWidth;
  1075. column.Visible = isDisplay;
  1076. }
  1077. catch { }
  1078. break;
  1079. }
  1080. }
  1081. }
  1082. }
  1083. /// <summary>
  1084. /// 设置列标题顺序
  1085. /// </summary>
  1086. /// <param name="columnDisplayString"></param>
  1087. /// <param name="column"></param>
  1088. public static void SetColumnDisplayIndex(string columnDisplayString, System.Windows.Forms.DataGridViewColumnCollection columns, System.Windows.Forms.ContextMenuStrip cmsGridViewDisplayMenu = null, string hiddenFields = "")
  1089. {
  1090. if (columnDisplayString == null)
  1091. {
  1092. columnDisplayString = "";
  1093. }
  1094. if (cmsGridViewDisplayMenu != null)
  1095. {
  1096. cmsGridViewDisplayMenu.Items.Clear();
  1097. }
  1098. for (int i = 0; i < columns.Count; i++)
  1099. {
  1100. SetColumnDisplayIndex(i, columnDisplayString, columns);
  1101. }
  1102. for (int i = 0; i < columns.Count; i++)
  1103. {
  1104. System.Windows.Forms.DataGridViewColumn column = columns[i];
  1105. if (!("," + hiddenFields.ToLower() + ",").Contains("," + column.Name.ToLower() + ","))
  1106. {
  1107. SetToolStripMenuItem(column, cmsGridViewDisplayMenu);
  1108. }
  1109. else
  1110. {
  1111. column.Visible = false;
  1112. }
  1113. }
  1114. }
  1115. // static string tempstr = "";
  1116. /// <summary>
  1117. /// 设置标题菜单项
  1118. /// </summary>
  1119. /// <param name="columnDisplayString"></param>
  1120. /// <param name="column"></param>
  1121. public static void SetToolStripMenuItem(System.Windows.Forms.DataGridViewColumn column, System.Windows.Forms.ContextMenuStrip cmsGridViewDisplayMenu = null)
  1122. {
  1123. bool isDisplay = column.Visible;
  1124. if (cmsGridViewDisplayMenu != null)
  1125. {
  1126. System.Windows.Forms.ToolStripMenuItem item = new System.Windows.Forms.ToolStripMenuItem();
  1127. item.Text = column.HeaderText;
  1128. item.Checked = isDisplay;
  1129. if (cmsGridViewDisplayMenu.Items.Count < 2)
  1130. {
  1131. item.Enabled = false;
  1132. }
  1133. if (column.HeaderText.ToLower() == "id")
  1134. {
  1135. item.Enabled = false;
  1136. }
  1137. cmsGridViewDisplayMenu.Items.Add(item);
  1138. column.HeaderCell.ContextMenuStrip = cmsGridViewDisplayMenu;
  1139. }
  1140. }
  1141. /// <summary>
  1142. /// 获取ColumnDisplayString列标题顺序字符串
  1143. /// </summary>
  1144. /// <param name="columns"></param>
  1145. /// <returns></returns>
  1146. public static string GetColumnDisplayString(System.Windows.Forms.DataGridViewColumnCollection columns)
  1147. {
  1148. string tempValue = "";
  1149. for (int i = 0; i < columns.Count; i++)
  1150. {
  1151. System.Windows.Forms.DataGridViewColumn column = columns[i];
  1152. tempValue += column.Name + ":" + column.DisplayIndex + ":" + column.Visible.ToString() + ":" + column.Width + "|";
  1153. }
  1154. return tempValue;
  1155. }
  1156. /// <summary>
  1157. /// 获取DataGridView唯一标识
  1158. /// </summary>
  1159. /// <param name="frmName"></param>
  1160. /// <param name="dataGridViewName"></param>
  1161. /// <returns></returns>
  1162. public static string GetDataGridViewUniquelyIdentify(string frmName, string dataGridViewName)
  1163. {
  1164. return frmName + "_" + dataGridViewName;
  1165. }
  1166. #region Web GET POST方式提交
  1167. static System.Net.SecurityProtocolType _HTTP_SecurityProtocolType = System.Net.SecurityProtocolType.Ssl3;
  1168. /// <summary>
  1169. /// Http 方式SSL安全协议
  1170. /// </summary>
  1171. public static System.Net.SecurityProtocolType HTTP_SecurityProtocolType
  1172. {
  1173. get { return CustomPublicMethod._HTTP_SecurityProtocolType; }
  1174. set { CustomPublicMethod._HTTP_SecurityProtocolType = value; }
  1175. }
  1176. static System.Net.SecurityProtocolType _HTTPS_SecurityProtocolType = System.Net.SecurityProtocolType.Tls;
  1177. /// <summary>
  1178. /// Https 方式SSL安全协议
  1179. /// </summary>
  1180. public static System.Net.SecurityProtocolType HTTPS_SecurityProtocolType
  1181. {
  1182. get { return CustomPublicMethod._HTTPS_SecurityProtocolType; }
  1183. set { CustomPublicMethod._HTTPS_SecurityProtocolType = value; }
  1184. }
  1185. public static void SetServicePointManagerSecurityProtocol(string url)
  1186. {
  1187. //这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
  1188. System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
  1189. if (url.ToLower().StartsWith("https"))
  1190. {
  1191. System.Net.ServicePointManager.SecurityProtocol = _HTTPS_SecurityProtocolType;
  1192. }
  1193. else
  1194. {
  1195. System.Net.ServicePointManager.SecurityProtocol = _HTTP_SecurityProtocolType;
  1196. }
  1197. }
  1198. //回调验证证书问题
  1199. public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  1200. {
  1201. // 总是接受
  1202. return true;
  1203. }
  1204. /// <summary>
  1205. /// 以Post 形式提交表单数据到 uri
  1206. /// </summary>
  1207. /// <param name="uri"></param>
  1208. /// <param name="files"></param>
  1209. /// <param name="values"></param>
  1210. /// <returns></returns>
  1211. public static string FormOrDataPost(string url, IEnumerable<UploadFile> files, NameValueCollection values, Encoding _Encoding = null)
  1212. {
  1213. System.GC.Collect();
  1214. if (_Encoding == null)
  1215. {
  1216. _Encoding = Encoding.Default;
  1217. }
  1218. string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
  1219. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  1220. request.ContentType = "multipart/form-data; boundary=" + boundary;
  1221. request.Method = "POST";
  1222. request.KeepAlive = true;
  1223. request.Credentials = CredentialCache.DefaultCredentials;
  1224. Stream requestStream = request.GetRequestStream();
  1225. //MemoryStream stream = new MemoryStream();
  1226. byte[] line = _Encoding.GetBytes("\r\n--" + boundary + "\r\n");
  1227. //提交文本字段
  1228. if (values != null)
  1229. {
  1230. string format = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
  1231. foreach (string key in values.Keys)
  1232. {
  1233. string s = string.Format(format, key, values[key]);
  1234. byte[] data = Encoding.UTF8.GetBytes(s);
  1235. requestStream.Write(data, 0, data.Length);
  1236. }
  1237. requestStream.Write(line, 0, line.Length);
  1238. }
  1239. //提交文件
  1240. if (files != null)
  1241. {
  1242. string fformat = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
  1243. foreach (UploadFile file in files)
  1244. {
  1245. string s = string.Format(fformat, file.Name, file.Filename);
  1246. byte[] data = Encoding.UTF8.GetBytes(s);
  1247. requestStream.Write(data, 0, data.Length);
  1248. byte[] filedata = file.Data;
  1249. if (file.Data != null)
  1250. {
  1251. requestStream.Write(file.Data, 0, file.Data.Length);
  1252. }
  1253. else
  1254. {
  1255. filedata = File.ReadAllBytes(file.Filename);
  1256. requestStream.Write(filedata, 0, filedata.Length);
  1257. }
  1258. requestStream.Write(line, 0, line.Length);
  1259. filedata = null;
  1260. }
  1261. }
  1262. // request.ContentLength = requestStream.Length;
  1263. requestStream.Close();
  1264. requestStream = null;
  1265. using (System.Net.WebResponse wr = request.GetResponse())
  1266. {
  1267. System.IO.StreamReader str = new System.IO.StreamReader(wr.GetResponseStream(), _Encoding);
  1268. string strMsg = str.ReadToEnd();
  1269. str.Close();
  1270. str.Dispose();
  1271. str = null;
  1272. request.Abort();
  1273. request = null;
  1274. strMsg = System.Web.HttpUtility.UrlDecode(strMsg);
  1275. return strMsg;
  1276. //在这里对接收到的页面内容进行处理
  1277. }
  1278. }
  1279. /// <summary>
  1280. /// Web POST方式提交
  1281. /// </summary>
  1282. /// <param name="url"></param>
  1283. /// <param name="postData"></param>
  1284. /// <param name="_Encoding">字符编码</param>
  1285. /// <param name="_ContentType"> Content-typeHTTP 标头的值</param>
  1286. /// <returns></returns>
  1287. public static string HttpWebRequestPOST(string url, string postData, Encoding _Encoding = null, string _ContentType = "application/x-www-form-urlencoded", CookieContainer myCookieContainer = null, bool isUrlDecode = true)
  1288. {
  1289. try
  1290. {
  1291. //string postData = "CustomerID=LYFZTYUF"
  1292. // + "&ShareTitle=" + System.Web.HttpUtility.UrlEncode("OK!Test")
  1293. // + "&ShareDescription=" + System.Web.HttpUtility.UrlEncode("利亚方舟微相册分享体验微 信号:340508706@qq.com");
  1294. System.GC.Collect();
  1295. if (_Encoding == null)
  1296. {
  1297. _Encoding = Encoding.Default;
  1298. }
  1299. byte[] byteArray = _Encoding.GetBytes(postData);
  1300. if (System.Net.ServicePointManager.DefaultConnectionLimit < 512)
  1301. {
  1302. System.Net.ServicePointManager.DefaultConnectionLimit = 512;
  1303. }
  1304. //这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
  1305. // System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
  1306. SetServicePointManagerSecurityProtocol(url);
  1307. // string url = "http://localhost:8000/webService/POSTText?t=" + DateTime.Now.ToString("yyyyMMddhhmmss"); //POST到网站
  1308. System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new Uri(url));
  1309. // System.Net.CookieContainer cookies = new System.Net.CookieContainer();
  1310. // webRequest.CookieContainer=cookies;
  1311. webRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
  1312. webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; Zune 4.7; BOIE9;ZHCN)";
  1313. webRequest.KeepAlive = false;
  1314. webRequest.ProtocolVersion = System.Net.HttpVersion.Version10;
  1315. webRequest.Method = "POST";
  1316. webRequest.ContentType = _ContentType;//"application/x-www-form-urlencoded";
  1317. webRequest.ContentLength = byteArray.Length;
  1318. if (myCookieContainer != null)
  1319. {
  1320. webRequest.CookieContainer = myCookieContainer;
  1321. }
  1322. System.IO.Stream newStream = webRequest.GetRequestStream();
  1323. newStream.Write(byteArray, 0, byteArray.Length);
  1324. newStream.Close();
  1325. newStream = null;
  1326. //接收返回信息:
  1327. webRequest.Timeout = 600000;
  1328. System.Threading.Thread.Sleep(10);
  1329. using (System.Net.WebResponse wr = webRequest.GetResponse())
  1330. {
  1331. System.IO.StreamReader str = new System.IO.StreamReader(wr.GetResponseStream(), _Encoding);
  1332. string strMsg = str.ReadToEnd();
  1333. str.Close();
  1334. str.Dispose();
  1335. str = null;
  1336. webRequest.Abort();
  1337. webRequest = null;
  1338. if (isUrlDecode)
  1339. {
  1340. strMsg = System.Web.HttpUtility.UrlDecode(strMsg);
  1341. }
  1342. return strMsg;
  1343. //在这里对接收到的页面内容进行处理
  1344. }
  1345. // System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)webRequest.GetResponse();
  1346. //cookies = (System.Net.CookieContainer)response.Cookies;
  1347. //System.Net.Cookie cookie = new System.Net.Cookie();
  1348. // System.Net.Cookie cookie = response.Cookies[0];
  1349. // System.Net.CookieCollection ck = cookies.GetCookies(webRequest.RequestUri);
  1350. /* System.IO.StreamReader stream = new System.IO.StreamReader(response.GetResponseStream(), Encoding.Default);
  1351. string Message = stream.ReadToEnd();
  1352. Message = System.Web.HttpUtility.UrlDecode(Message);
  1353. stream.Close();
  1354. response.Close();
  1355. webRequest.Abort();
  1356. return Message;*/
  1357. }
  1358. catch (Exception ex)
  1359. {
  1360. try
  1361. {
  1362. return HttpContentPOST(url, postData);
  1363. }
  1364. catch
  1365. {
  1366. System.Net.ServicePointManager.Expect100Continue = false;
  1367. return "Request failed,Exception:" + ex.Message;
  1368. }
  1369. }
  1370. }
  1371. // string postData = "";
  1372. // System.Net.Http.HttpContent content = new System.Net.Http.StringContent(postData);
  1373. //var result = client.PostAsync(url, content).Result;
  1374. /// <summary>
  1375. /// Web HttpClient GET方式提交
  1376. /// </summary>
  1377. /// <param name="url"></param>
  1378. /// <param name="_Encoding"></param>
  1379. /// <returns></returns>
  1380. public static string HttpContentGET(string url, Encoding _Encoding = null)
  1381. {
  1382. string resultStr = "";
  1383. SetServicePointManagerSecurityProtocol(url);
  1384. System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
  1385. var result = client.GetAsync(url).Result;
  1386. resultStr = result.Content.ReadAsStringAsync().Result;
  1387. client.Dispose();
  1388. return System.Web.HttpUtility.UrlDecode(resultStr);
  1389. }
  1390. /// <summary>
  1391. /// Web HttpClient POST方式提交
  1392. /// </summary>
  1393. /// <param name="url"></param>
  1394. /// <param name="postData"></param>
  1395. /// <param name="_Encoding"></param>
  1396. /// <returns></returns>
  1397. public static string HttpContentPOST(string url, string postData, Encoding _Encoding = null)
  1398. {
  1399. string resultStr = "";
  1400. SetServicePointManagerSecurityProtocol(url);
  1401. System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
  1402. System.Net.Http.HttpContent content = new System.Net.Http.StringContent(postData);
  1403. var result = client.PostAsync(url, content).Result;
  1404. resultStr = result.Content.ReadAsStringAsync().Result;
  1405. client.Dispose();
  1406. return System.Web.HttpUtility.UrlDecode(resultStr);
  1407. }
  1408. /// <summary>
  1409. /// Web GET方式提交
  1410. /// </summary>
  1411. /// <param name="url"></param>
  1412. /// <param name="_Encoding">字符编码</param>
  1413. /// <returns></returns>
  1414. public static string HttpWebRequestGET(string url, Encoding _Encoding = null, CookieContainer myCookieContainer = null, bool isUrlDecode = true, string _ContentType = null)
  1415. {
  1416. try
  1417. {
  1418. System.GC.Collect();
  1419. if (_Encoding == null)
  1420. {
  1421. _Encoding = Encoding.Default;
  1422. }
  1423. // Random random = new Random();
  1424. // string url = "http://192.168.1.141:8000/webService/getuserinfo?account=111111&password=1234&t="+ DateTime.Now.ToString("yyyyMMddhhmmss");
  1425. if (System.Net.ServicePointManager.DefaultConnectionLimit < 512)
  1426. {
  1427. System.Net.ServicePointManager.DefaultConnectionLimit = 512;
  1428. }
  1429. SetServicePointManagerSecurityProtocol(url);
  1430. System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
  1431. webRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/json,*/*";
  1432. webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; Zune 4.7; BOIE9;ZHCN)";
  1433. webRequest.Method = "GET";
  1434. webRequest.Timeout = 600000;
  1435. webRequest.KeepAlive = false;
  1436. webRequest.ProtocolVersion = System.Net.HttpVersion.Version10;
  1437. if (_ContentType != null)
  1438. {
  1439. webRequest.ContentType = _ContentType;
  1440. }
  1441. if (myCookieContainer != null)
  1442. {
  1443. webRequest.CookieContainer = myCookieContainer;
  1444. }
  1445. System.Threading.Thread.Sleep(5);
  1446. using (System.Net.WebResponse wr = webRequest.GetResponse())
  1447. {
  1448. System.IO.StreamReader str = new System.IO.StreamReader(wr.GetResponseStream(), _Encoding);
  1449. string strMsg = str.ReadToEnd();
  1450. str.Close();
  1451. str.Dispose();
  1452. str = null;
  1453. webRequest.Abort();
  1454. webRequest = null;
  1455. if (isUrlDecode)
  1456. {
  1457. strMsg = System.Web.HttpUtility.UrlDecode(strMsg);
  1458. }
  1459. return strMsg;
  1460. //在这里对接收到的页面内容进行处理
  1461. }
  1462. // System.Net.HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse();
  1463. // System.IO.Stream imgStream = webResponse.GetResponseStream();
  1464. // System.IO.StreamReader stream = new System.IO.StreamReader(imgStream, Encoding.Default);
  1465. // string Message = stream.ReadToEnd();
  1466. // Message = System.Web.HttpUtility.UrlDecode(Message);
  1467. // stream.Close();
  1468. // webResponse.Close();
  1469. // webRequest.Abort();
  1470. // return Message;
  1471. }
  1472. catch (Exception ex)
  1473. {
  1474. try
  1475. {
  1476. return HttpContentGET(url);
  1477. }
  1478. catch
  1479. {
  1480. System.Net.ServicePointManager.Expect100Continue = false;
  1481. return "Request failed,Exception:" + ex.Message;
  1482. }
  1483. }
  1484. }
  1485. /// <summary>
  1486. /// 获取Http网络图片
  1487. /// </summary>
  1488. /// <param name="url"></param>
  1489. /// <returns></returns>
  1490. public static Image GetHttpWebRequestImage(string url)
  1491. {
  1492. System.IO.Stream imgStream = System.Net.WebRequest.Create(url).GetResponse().GetResponseStream();
  1493. Image obj = Image.FromStream(imgStream);
  1494. Image retobj = (Image)obj.Clone();
  1495. imgStream.Close();
  1496. imgStream.Dispose();
  1497. imgStream = null;
  1498. obj.Dispose();
  1499. obj = null;
  1500. return retobj;
  1501. }
  1502. /// <summary>
  1503. /// 获取Http网络图片
  1504. /// </summary>
  1505. /// <param name="url"></param>
  1506. /// <returns></returns>
  1507. public static Bitmap GetHttpWebRequestBitmap(string url)
  1508. {
  1509. System.IO.Stream imgStream = (new System.Net.WebClient()).OpenRead(url);
  1510. Bitmap obj = new Bitmap(imgStream);
  1511. Bitmap retobj = (Bitmap)obj.Clone();
  1512. imgStream.Close();
  1513. imgStream.Dispose();
  1514. imgStream = null;
  1515. obj.Dispose();
  1516. obj = null;
  1517. return retobj;
  1518. }
  1519. #endregion
  1520. #region 短信发送相关方法
  1521. /// <summary>
  1522. /// 验证手机号 返回空值时为验证通过, 如果有错误格式手机号时返回错误手机号字符串
  1523. /// </summary>
  1524. /// <param name="phoneStr">要验证的手机字符串,多个手机号以“,”号分隔</param>
  1525. /// <returns>返回空值时为验证通过,如果有错误格式手机号时返回错误手机号字符串</returns>
  1526. public static string ValidationPhones(string phoneStr)
  1527. {
  1528. string tempLawfulPhone = "";
  1529. return ValidationPhones(phoneStr, ref tempLawfulPhone);
  1530. }
  1531. static List<string> _FilterMobileNumberList = new List<string>();
  1532. /// <summary>
  1533. /// 要过虑的手机号集合
  1534. /// </summary>
  1535. public static List<string> FilterMobileNumberList
  1536. {
  1537. get { return CustomPublicMethod._FilterMobileNumberList; }
  1538. set { CustomPublicMethod._FilterMobileNumberList = value; }
  1539. }
  1540. /// <summary>
  1541. /// 验证手机号 返回空值时为验证通过, 如果有错误格式手机号时返回错误手机号字符串
  1542. /// </summary>
  1543. /// <param name="phoneStr">要验证的手机字符串,多个手机号以“,”号分隔</param>
  1544. /// <param name="lawfulPhone">返回正确的手机号</param>
  1545. /// <returns>返回空值时为验证通过,如果有错误格式手机号时返回错误手机号字符串</returns>
  1546. public static string ValidationPhones(string phoneStr, ref string lawfulPhone)
  1547. {
  1548. string ErrorPhone = "";
  1549. string CorrectPhone = "";//有效手机号
  1550. string[] phones = phoneStr.Trim().Split(',');
  1551. if (phoneStr.Length < 11)
  1552. {
  1553. ErrorPhone += phoneStr;
  1554. }
  1555. else
  1556. {
  1557. lawfulPhone = "";
  1558. foreach (string phone in phones)
  1559. {
  1560. if (phone.Trim().Length > 0)
  1561. {
  1562. long phoneDigital = 0;
  1563. if (phone.IndexOf("1") == 0 && phone.Length == 11 && long.TryParse(phone, out phoneDigital) && !FilterMobileNumberList.Contains(phone))
  1564. {
  1565. if (phone.IndexOf("11") == 0 || phone.IndexOf("12") == 0)
  1566. {
  1567. ErrorPhone += phone + ",";
  1568. }
  1569. else
  1570. {
  1571. if (!lawfulPhone.Contains(phone))
  1572. {
  1573. CorrectPhone += phone;
  1574. lawfulPhone += phone + ",";
  1575. }
  1576. }
  1577. }
  1578. else
  1579. {
  1580. ErrorPhone += phone + ",";
  1581. }
  1582. }
  1583. }
  1584. }
  1585. //去除结尾多余的“,”
  1586. if (lawfulPhone.Length >= 11)
  1587. {
  1588. if (lawfulPhone.ToString().LastIndexOf(',') == lawfulPhone.Length - 1)
  1589. {
  1590. lawfulPhone = lawfulPhone.Remove(lawfulPhone.Length - 1, 1);
  1591. }
  1592. }
  1593. if (CorrectPhone.Trim().Length <= 0)
  1594. {
  1595. ErrorPhone = "没找到有效的手机号码!";
  1596. }
  1597. return ErrorPhone.Trim().Trim(',');
  1598. }
  1599. /// <summary>
  1600. /// 获取字符串中的退订字符
  1601. /// </summary>
  1602. /// <param name="s"></param>
  1603. /// <returns></returns>
  1604. static string GetUnsubscribeCharacter(string s)
  1605. {
  1606. string retstr = "";
  1607. if (s.ToUpper().Contains("回TD退订"))
  1608. {
  1609. retstr = "回TD退订";
  1610. }
  1611. else if (s.ToUpper().Contains("退订回TD"))
  1612. {
  1613. retstr = "退订回TD";
  1614. }
  1615. else if (s.ToUpper().Contains("退订回N"))
  1616. {
  1617. retstr = "退订回N";
  1618. }
  1619. else if (s.ToUpper().Contains("回N退订"))
  1620. {
  1621. retstr = "回N退订";
  1622. }
  1623. else if (s.ToUpper().Contains("退订N"))
  1624. {
  1625. retstr = "退订N";
  1626. }
  1627. else if (s.ToUpper().Contains("回复TD退订"))
  1628. {
  1629. retstr = "回复TD退订";
  1630. }
  1631. else if (s.ToUpper().Contains("退订复回TD"))
  1632. {
  1633. retstr = "退订回复TD";
  1634. }
  1635. else if (s.ToUpper().Contains("TD退订"))
  1636. {
  1637. retstr = "TD退订";
  1638. }
  1639. else if (s.ToUpper().Contains("退订TD"))
  1640. {
  1641. retstr = "退订TD";
  1642. }
  1643. return retstr;
  1644. }
  1645. /// <summary>
  1646. /// 获取短信内容条数 并在最后一条为一个符号时去除符号
  1647. /// </summary>
  1648. /// <param name="s"></param>
  1649. /// <param name="signature">签名字符 如:“【利亚方州】”</param>
  1650. /// <returns></returns>
  1651. public static int GetSendSmsCount(ref string s, string signature)
  1652. {
  1653. int count = 0;
  1654. // string UnsubscribeCharacter = GetUnsubscribeCharacter(s);
  1655. string tempStr = s;//.Replace(UnsubscribeCharacter.ToUpper(), "").Replace(UnsubscribeCharacter.ToLower(), "");
  1656. bool isSignatureFront = false;//签名是否在前面
  1657. if (signature != null)
  1658. {
  1659. if (tempStr.IndexOf(signature) == 0)
  1660. {
  1661. //签名在前面
  1662. isSignatureFront = true;
  1663. tempStr = tempStr.Substring(signature.Length);
  1664. }
  1665. else if (tempStr.IndexOf(signature) == (tempStr.Length - signature.Length))
  1666. {
  1667. //签名在后面
  1668. tempStr = tempStr.Substring(0, tempStr.Length - signature.Length);
  1669. isSignatureFront = false;
  1670. }
  1671. tempStr = tempStr.Replace(signature, "");
  1672. }
  1673. if (s.Length > 70)
  1674. {
  1675. count = s.Length / 67;
  1676. int Remainder = (s.Length % 67);
  1677. if (Remainder > 0)
  1678. {
  1679. count++;
  1680. }
  1681. if (Remainder == 1 || s.Length == 71)
  1682. {
  1683. string tempFilterChar = ",,.。??!!()(){}[]【】<>《》;::*%';|\\+-=*&^%$#@!~`";
  1684. string LastChar = tempStr.Substring(tempStr.Length - 1);
  1685. if (tempFilterChar.Contains(LastChar))
  1686. {
  1687. tempStr = tempStr.Substring(0, tempStr.Length - 1);
  1688. }
  1689. else
  1690. {
  1691. LastChar = tempStr.Substring(0, 1);
  1692. if (tempFilterChar.Contains(LastChar))
  1693. {
  1694. tempStr = tempStr.Substring(1, tempStr.Length - 1);
  1695. }
  1696. else
  1697. {
  1698. int lastIndx1 = tempStr.LastIndexOf('!');
  1699. int lastIndx2 = tempStr.LastIndexOf('!');
  1700. int lastIndx3 = tempStr.LastIndexOf('.');
  1701. int lastIndx4 = tempStr.LastIndexOf('。');
  1702. if (lastIndx1 != -1)
  1703. {
  1704. tempStr = tempStr.Remove(lastIndx1, 1);
  1705. }
  1706. else if (lastIndx2 != -1)
  1707. {
  1708. tempStr = tempStr.Remove(lastIndx2, 1);
  1709. }
  1710. else if (lastIndx3 != -1)
  1711. {
  1712. tempStr = tempStr.Remove(lastIndx3, 1);
  1713. }
  1714. else if (lastIndx4 != -1)
  1715. {
  1716. tempStr = tempStr.Remove(lastIndx4, 1);
  1717. }
  1718. else
  1719. {
  1720. lastIndx1 = tempStr.LastIndexOf(',');
  1721. lastIndx2 = tempStr.LastIndexOf(',');
  1722. if (lastIndx1 != -1)
  1723. {
  1724. tempStr = tempStr.Remove(lastIndx1, 1);
  1725. }
  1726. else if (lastIndx2 != -1)
  1727. {
  1728. tempStr = tempStr.Remove(lastIndx2, 1);
  1729. }
  1730. }
  1731. }
  1732. }
  1733. if (isSignatureFront)
  1734. {
  1735. s = signature + tempStr.Replace("\r\n", "");
  1736. }
  1737. else
  1738. {
  1739. s = tempStr.Replace("\r\n", "") + signature;
  1740. }
  1741. }
  1742. }
  1743. else if (s.Length > 0)
  1744. {
  1745. count = 1;
  1746. }
  1747. /* if (UnsubscribeCharacter.Trim().Length > 0)
  1748. {
  1749. s = s.Replace(UnsubscribeCharacter.ToUpper(), "").Replace(UnsubscribeCharacter.ToLower(), "");
  1750. s = s + UnsubscribeCharacter.ToUpper();
  1751. }*/
  1752. return count;
  1753. }
  1754. /// <summary>
  1755. /// 获取以","分隔的手机号 以指定手机号个数拆分成数组
  1756. /// </summary>
  1757. /// <param name="phoneString">以","分隔的手机号</param>
  1758. /// <param name="count"></param>
  1759. /// <returns></returns>
  1760. public static string[] GetPhoneSplitCount(string phoneString, int count)
  1761. {
  1762. string[] tempPhones = phoneString.Trim().Split(',');
  1763. List<string> tempPhoneList = new List<string>();
  1764. tempPhoneList.AddRange(tempPhones);
  1765. tempPhoneList.Sort();
  1766. tempPhones = tempPhoneList.ToArray();
  1767. tempPhoneList.Clear();
  1768. int tempCount = 0;
  1769. string tempPhoneStr = "";
  1770. for (int i = 0; i < tempPhones.Length; i++)
  1771. {
  1772. tempCount++;
  1773. if (tempCount == count)
  1774. {
  1775. tempPhoneStr += tempPhones[i];
  1776. tempCount = 0;
  1777. tempPhoneStr += "|";
  1778. }
  1779. else
  1780. {
  1781. if (tempPhoneStr == "")
  1782. {
  1783. tempPhoneStr += tempPhones[i];
  1784. }
  1785. else
  1786. {
  1787. tempPhoneStr += "," + tempPhones[i];
  1788. }
  1789. }
  1790. }
  1791. if (tempPhoneStr.Trim('|').Length > 0)
  1792. {
  1793. return tempPhoneStr.Trim('|').Split('|');
  1794. }
  1795. else
  1796. {
  1797. return new string[0];
  1798. }
  1799. }
  1800. /// <summary>
  1801. /// 域名转换为IP地址
  1802. /// </summary>
  1803. /// <param name="hostname">域名或IP地址 ""</param>
  1804. /// <param name="isIP6">是否获取IP6地址</param>
  1805. /// <returns>IP地址</returns>
  1806. public static string HostnameToIP(string hostname, bool isIP6 = false)
  1807. {
  1808. string ipStr = hostname;
  1809. try
  1810. {
  1811. System.Net.IPAddress[] IPs = System.Net.Dns.GetHostAddresses(hostname);
  1812. foreach (System.Net.IPAddress ip in IPs)
  1813. {
  1814. string tempStr = ip.ToString();
  1815. if (isIP6)
  1816. {
  1817. string[] temps = tempStr.Split(':');
  1818. if (temps.Length == 8)
  1819. {
  1820. ipStr = tempStr;
  1821. break;
  1822. }
  1823. }
  1824. else
  1825. {
  1826. string[] temps = tempStr.Split('.');
  1827. if (temps.Length == 4)
  1828. {
  1829. ipStr = tempStr;
  1830. break;
  1831. }
  1832. }
  1833. }
  1834. }
  1835. catch (Exception)
  1836. {
  1837. throw new Exception("转换IP地址错误");
  1838. }
  1839. return ipStr;
  1840. }
  1841. #endregion
  1842. /// <summary>
  1843. /// 过虑特殊字符
  1844. /// </summary>
  1845. /// <param name="characterString"></param>
  1846. /// <returns></returns>
  1847. public static string WorryingTooSpecialCharacter(string characterString)
  1848. {
  1849. return characterString
  1850. .Replace(".", "")
  1851. .Replace("*", "")
  1852. .Replace("<", "")
  1853. .Replace(">", "")
  1854. .Replace("/", "")
  1855. .Replace("\\", "")
  1856. .Replace("\"", "")
  1857. .Replace("|", "")
  1858. .Replace(":", "")
  1859. .Replace("?", "");
  1860. }
  1861. /// <summary>
  1862. /// 获取完整路径 只能为文件夹目录路径 检查路径结尾是否存在 “\”符号 如果不存在添加上
  1863. /// </summary>
  1864. /// <param name="directoryPath"></param>
  1865. /// <returns></returns>
  1866. public static string GetFullDirectoryPath(string directoryPath)
  1867. {
  1868. if (directoryPath.LastIndexOf("\\") != directoryPath.Length - 1)
  1869. {
  1870. directoryPath = directoryPath + "\\";
  1871. }
  1872. return directoryPath;
  1873. }
  1874. /// <summary>
  1875. /// 删除Thumbs.db 文件
  1876. /// </summary>
  1877. /// <param name="directoryPath"></param>
  1878. public static void DeleteThumbs(string directoryPath)
  1879. {
  1880. LYFZ.WinAPI.CustomPublicMethod.ExecuteCmd("del " + GetFullDirectoryPath(directoryPath) + "Thumbs.db /f/s/q/a");
  1881. }
  1882. /// <summary>
  1883. /// 删除空文件夹
  1884. /// </summary>
  1885. /// <param name="directoryPath">文件夹路径</param>
  1886. public static void DeleteDirectory(string directoryPath)
  1887. {
  1888. DeleteThumbs(directoryPath);
  1889. string[] directorys = System.IO.Directory.GetDirectories(directoryPath, "*", System.IO.SearchOption.AllDirectories);
  1890. foreach (string dir in directorys)
  1891. {
  1892. try
  1893. {
  1894. DeleteThumbs(directoryPath);
  1895. if (System.IO.Directory.GetFiles(dir).Length <= 0)
  1896. {
  1897. System.IO.Directory.Delete(dir);
  1898. }
  1899. }
  1900. catch { }
  1901. }
  1902. try
  1903. {
  1904. if (System.IO.Directory.GetFiles(directoryPath).Length <= 0)
  1905. {
  1906. System.IO.Directory.Delete(directoryPath);
  1907. }
  1908. }
  1909. catch { }
  1910. }
  1911. /// <summary>
  1912. /// 执行CMD命令
  1913. /// </summary>
  1914. /// <param name="command">CMD命令字符串</param>
  1915. /// <returns></returns>
  1916. public static string ExecuteCmd(string command)
  1917. {
  1918. string str = command;
  1919. System.Diagnostics.Process p = new System.Diagnostics.Process();
  1920. p.StartInfo.FileName = "cmd.exe";
  1921. p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
  1922. p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
  1923. p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
  1924. p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
  1925. p.StartInfo.CreateNoWindow = true;//不显示程序窗口
  1926. p.Start();//启动程序
  1927. //向cmd窗口发送输入信息
  1928. p.StandardInput.WriteLine(str + " &exit");
  1929. p.StandardInput.AutoFlush = true;
  1930. //p.StandardInput.WriteLine("exit");
  1931. //向标准输入写入要执行的命令。这里使用&是批处理命令的符号,表示前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死
  1932. //同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令,后者表示必须前一个命令执行失败才会执行后面的命令
  1933. //获取cmd窗口的输出信息
  1934. string output = p.StandardOutput.ReadToEnd();
  1935. p.WaitForExit();//等待程序执行完退出进程
  1936. p.Close();
  1937. return output;
  1938. }
  1939. /// <summary>
  1940. /// 获取时间为"1900-01-01"的日期对象
  1941. /// </summary>
  1942. /// <returns></returns>
  1943. public static DateTime GetNullDateTime()
  1944. {
  1945. return Convert.ToDateTime("1900-01-01");
  1946. }
  1947. /// <summary>
  1948. /// 追加写入
  1949. /// </summary>
  1950. /// <param name="fullPath"></param>
  1951. /// <param name="txt"></param>
  1952. public static void AddWriter(string fullPath, string txt)
  1953. {
  1954. using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fullPath, true, Encoding.UTF8))
  1955. {
  1956. sw.WriteLine(txt);
  1957. sw.Flush();
  1958. sw.Close(); System.IO.File.WriteAllText(fullPath, "", Encoding.UTF8);
  1959. }
  1960. }
  1961. /// <summary>
  1962. /// 覆盖写入
  1963. /// </summary>
  1964. /// <param name="fullPath"></param>
  1965. /// <param name="txt"></param>
  1966. public static void CoverWriter(string fullPath, string txt)
  1967. {
  1968. System.IO.File.WriteAllText(fullPath, txt, Encoding.UTF8);
  1969. }
  1970. /// <summary>
  1971. /// 获取机器硬件码
  1972. /// </summary>
  1973. /// <returns></returns>
  1974. public static string GetHardwareCode()
  1975. {
  1976. string TempHardwareCode = "";
  1977. TempHardwareCode = GetHDIDInfo() + "-" + GetNetCardMacAddress() + "-" + GetCpuInfo();
  1978. if (TempHardwareCode == "NOHDID-NOMAC-NOCPUSN")
  1979. {
  1980. TempHardwareCode = "机器硬件码获取失败!";
  1981. }
  1982. return TempHardwareCode;
  1983. }
  1984. /// <summary>
  1985. /// 获取机器硬件码
  1986. /// </summary>
  1987. /// <returns></returns>
  1988. public static string GetHardwareCodeOne()
  1989. {
  1990. string TempHardwareCode = GetHDIDInfo() + "-" + GetCpuInfo();
  1991. return TempHardwareCode.Replace("\"", "").Replace("&", "").Replace("#", "").Replace("$", "");
  1992. }
  1993. /// <summary>
  1994. /// cpu序列号
  1995. /// </summary>
  1996. /// <returns></returns>
  1997. public static string GetCpuInfo()
  1998. {
  1999. try
  2000. {
  2001. string cpuInfo = "";//cpu序列号
  2002. System.Management.ManagementClass cimobject = new System.Management.ManagementClass("Win32_Processor");
  2003. System.Management.ManagementObjectCollection moc = cimobject.GetInstances();
  2004. foreach (System.Management.ManagementObject mo in moc)
  2005. {
  2006. /*List<string> tmepList = new List<string>();
  2007. foreach (System.Management.PropertyData pdc in mo.Properties)
  2008. {
  2009. string valueStr = "";
  2010. if (pdc.Value != null) {
  2011. valueStr = pdc.Value.ToString();
  2012. }
  2013. tmepList.Add(pdc.Name + "|" + valueStr);
  2014. }*/
  2015. cpuInfo += mo.Properties["ProcessorId"].Value.ToString();
  2016. }
  2017. return ("CPUSN" + cpuInfo.ToString().Replace("-", ""));
  2018. }
  2019. catch
  2020. {
  2021. return "NOCPUSN";
  2022. }
  2023. }
  2024. /// <summary>
  2025. /// 获取硬盘ID
  2026. /// </summary>
  2027. /// <returns></returns>
  2028. public static string GetHDIDInfo()
  2029. {
  2030. try
  2031. {
  2032. string HDid = "";
  2033. System.Management.ManagementClass cimobject1 = new System.Management.ManagementClass("Win32_DiskDrive");
  2034. System.Management.ManagementObjectCollection moc1 = cimobject1.GetInstances();
  2035. foreach (System.Management.ManagementObject mo in moc1)
  2036. {
  2037. string modelValue = (string)mo.Properties["Model"].Value;
  2038. if (!modelValue.Contains("USB Device"))
  2039. {
  2040. HDid += "SN:" + mo.Properties["SerialNumber"].Value.ToString().Trim() + modelValue;
  2041. }
  2042. }
  2043. return ("HDID-" + HDid.ToString().Trim().Replace("-", "")).Trim().Replace(" ", "").ToUpper().Replace("DiskDevice".ToUpper(), "");
  2044. }
  2045. catch
  2046. {
  2047. return "NOHDID" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
  2048. }
  2049. }
  2050. /// <summary>
  2051. /// C盘序列号
  2052. /// </summary>
  2053. /// <returns></returns>
  2054. public static string GetDiskVolumeSerialNumber()
  2055. {
  2056. System.Management.ManagementObject disk;
  2057. disk = new System.Management.ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
  2058. disk.Get();
  2059. return disk.GetPropertyValue("VolumeSerialNumber").ToString();
  2060. }
  2061. /// <summary>
  2062. /// 获取MAC地址
  2063. /// </summary>
  2064. /// <returns></returns>
  2065. public static string GetNetCardMacAddress(string separator = "")
  2066. {
  2067. try
  2068. {
  2069. LYFZ.WinAPI.LocalNetworkCardObjects networkCarObjects = new WinAPI.LocalNetworkCardObjects();
  2070. string retMacStr = "";
  2071. if (networkCarObjects.PhysicalNICList.Count > 0)
  2072. {
  2073. retMacStr = "PhysicalNICList:";
  2074. foreach (NetworkCardInfo cardinfo in networkCarObjects.PhysicalNICList)
  2075. {
  2076. retMacStr += cardinfo.MACPhysicalAddress.ToString() + "&";
  2077. }
  2078. }
  2079. else if (networkCarObjects.WirelessLANList.Count > 0)
  2080. {
  2081. retMacStr = "WirelessLANList:";
  2082. foreach (NetworkCardInfo cardinfo in networkCarObjects.WirelessLANList)
  2083. {
  2084. retMacStr += cardinfo.MACPhysicalAddress.ToString() + "&";
  2085. }
  2086. }
  2087. else if (networkCarObjects.VirtualNetworkCardList.Count > 0)
  2088. {
  2089. retMacStr = "VirtualNetworkCardList:";
  2090. foreach (NetworkCardInfo cardinfo in networkCarObjects.VirtualNetworkCardList)
  2091. {
  2092. retMacStr += cardinfo.MACPhysicalAddress.ToString() + "&";
  2093. }
  2094. }
  2095. else
  2096. {
  2097. System.Management.ManagementClass mc;
  2098. System.Management.ManagementObjectCollection moc;
  2099. mc = new System.Management.ManagementClass("Win32_NetworkAdapterConfiguration");
  2100. moc = mc.GetInstances();
  2101. string str = "";
  2102. foreach (System.Management.ManagementObject mo in moc)
  2103. {
  2104. if ((bool)mo["IPEnabled"] == true)
  2105. {
  2106. str = mo["MacAddress"].ToString();
  2107. break;
  2108. }
  2109. }
  2110. return "ManagementClass-" + str.ToUpper().Replace(":", separator).Replace("-", separator);
  2111. }
  2112. return retMacStr.Trim('&');
  2113. }
  2114. catch
  2115. {
  2116. return "NOMAC-" + GetHDIDInfo();
  2117. }
  2118. /* // 获取属性
  2119. string caption = mo["Caption"].ToString(); //名称
  2120. string[] addresses = (string[])mo["IPAddress"]; //IP地址
  2121. string[] subnets = (string[])mo["IPSubnet"]; //子网掩码
  2122. string[] gateways = (string[])mo["DefaultIPGateway"]; //网关
  2123. string[] dnses = (string[])mo["DNSServerSearchOrder"]; //DNS
  2124. ManagementBaseObject newIP;
  2125. // 修改IP及子网掩码
  2126. newIP = mo.GetMethodParameters("EnableStatic");
  2127. newIP["IPAddress"] = new string[] { "192.168.2.51" };
  2128. newIP["SubnetMask"] = new string[] { "255.255.255.0" }; //修改IP同时,需要填写子网掩码
  2129. mo.InvokeMethod("EnableStatic", newIP, null);
  2130. // 设置网关地址
  2131. newIP = mo.GetMethodParameters("SetGateways");
  2132. newIP["DefaultIPGateway"] = new string[] { "192.168.2.1" };
  2133. mo.InvokeMethod("SetGateways", newIP, null);
  2134. // 设置DNS
  2135. newIP = mo.GetMethodParameters("SetDNSServerSearchOrder");
  2136. newIP["DNSServerSearchOrder"] = new string[] { "192.168.1.10" };
  2137. mo.InvokeMethod("SetDNSServerSearchOrder", newIP, null);*/
  2138. }
  2139. /// 显示本机各网卡的详细信息
  2140. ///
  2141. /// <summary>
  2142. /// 指定秒数后关机
  2143. /// </summary>
  2144. /// <param name="time"></param>
  2145. public static void ExitWindows(int time = 600)
  2146. {
  2147. ExecuteCmd("shutdown -s -t " + time.ToString());
  2148. }
  2149. /// <summary>
  2150. /// 取消关机命令
  2151. /// </summary>
  2152. /// <param name="time"></param>
  2153. public static void CancelExitWindows()
  2154. {
  2155. ExecuteCmd("shutdown -a");
  2156. }
  2157. /// <summary>
  2158. /// 获取指定路径目录的容量信息
  2159. /// </summary>
  2160. /// <param name="dirPath">获取指定路径目录</param>
  2161. /// <returns></returns>
  2162. public static MyDriverInfo GetDiskFreeSpace(string dirPath)
  2163. {
  2164. MyDriverInfo dInfo = new MyDriverInfo();
  2165. try
  2166. {
  2167. long freeBytes = 0;//可用大小
  2168. long totalBytes = 0;//
  2169. long totalFreeBytes = 0;
  2170. dInfo.DriverPath = dirPath;
  2171. if (Win32.GetDiskFreeSpace(dirPath, ref freeBytes, ref totalBytes, ref totalFreeBytes))
  2172. {
  2173. dInfo.FreeBytes = freeBytes;
  2174. dInfo.TotalBytes = totalBytes;
  2175. dInfo.TotalFreeBytes = totalFreeBytes;
  2176. dInfo.ErrorMessages = "";
  2177. }
  2178. else
  2179. {
  2180. int errCode = System.Runtime.InteropServices.Marshal.GetLastWin32Error();//获取错误码。
  2181. dInfo.ErrorMessages = Win32.GetSysErrMsg(errCode);
  2182. }
  2183. }
  2184. catch (Exception ex)
  2185. {
  2186. dInfo.DriverPath = dirPath;
  2187. dInfo.ErrorMessages = ex.Message;
  2188. }
  2189. return dInfo;
  2190. }
  2191. /// <summary>
  2192. /// 获取系统物理总内存大小
  2193. /// </summary>
  2194. /// <returns>内存大小(单位M)</returns>
  2195. public static int GetPhisicalMemory()
  2196. {
  2197. try
  2198. {
  2199. System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(); //用于查询一些如系统信息的管理对象
  2200. searcher.Query = new System.Management.SelectQuery("Win32_PhysicalMemory ", "", new string[] { "Capacity" });//设置查询条件
  2201. System.Management.ManagementObjectCollection collection = searcher.Get(); //获取内存容量
  2202. System.Management.ManagementObjectCollection.ManagementObjectEnumerator em = collection.GetEnumerator();
  2203. long capacity = 0;
  2204. while (em.MoveNext())
  2205. {
  2206. System.Management.ManagementBaseObject baseObj = em.Current;
  2207. if (baseObj.Properties["Capacity"].Value != null)
  2208. {
  2209. try
  2210. {
  2211. capacity += long.Parse(baseObj.Properties["Capacity"].Value.ToString());
  2212. }
  2213. catch
  2214. {
  2215. return 0;
  2216. }
  2217. }
  2218. baseObj.Dispose();
  2219. }
  2220. searcher.Dispose();
  2221. collection.Dispose();
  2222. em.Dispose();
  2223. return (int)(capacity / 1024 / 1024);
  2224. }
  2225. catch
  2226. {
  2227. return 0;
  2228. }
  2229. }
  2230. /// <summary>
  2231. /// 获取系统物理可用内存大小
  2232. /// </summary>
  2233. /// <returns>内存大小(单位M)</returns>
  2234. public static int GetPhisicalUsableMemory()
  2235. {
  2236. try
  2237. {
  2238. double available = 0;
  2239. //获取内存可用大小
  2240. System.Management.ManagementClass cimobject2 = new System.Management.ManagementClass("Win32_PerfFormattedData_PerfOS_Memory");
  2241. System.Management.ManagementObjectCollection moc2 = cimobject2.GetInstances();
  2242. foreach (System.Management.ManagementObject mo2 in moc2)
  2243. {
  2244. available += Int64.Parse(mo2.Properties["AvailableMBytes"].Value.ToString());
  2245. }
  2246. moc2.Dispose();
  2247. cimobject2.Dispose();
  2248. return Convert.ToInt32(available);
  2249. }
  2250. catch
  2251. {
  2252. return 0;
  2253. }
  2254. }
  2255. public static bool DataGridViewToExcel(string savePath, System.Windows.Forms.DataGridView m_DataView, BackgroundWorker backgroundWorker = null)
  2256. {
  2257. bool ret = false;
  2258. string FileName = savePath;
  2259. if (File.Exists(FileName))
  2260. {
  2261. File.Delete(FileName);
  2262. }
  2263. Biff8Excel.Excel.ExcelWorkbook wbook;
  2264. Biff8Excel.Excel.ExcelWorksheet wsheet;
  2265. //ExcelRow row;
  2266. // Biff8Excel.Excel.ExcelCellLinkDictionary row;
  2267. // Biff8Excel.Excel.ExcelCell cell;
  2268. Biff8Excel.Excel.ExcelCellStyle style;
  2269. //short x;
  2270. // Create a Workbook Object and set a password to make it read-only
  2271. //创建一个工作簿对象并设置密码,使其只读
  2272. wbook = new Biff8Excel.Excel.ExcelWorkbook();
  2273. wbook.SetDefaultFont("Arial", 10); // default to Arial,10
  2274. //wbook.Password = "Excel";
  2275. // Create 5 Worksheets
  2276. //创建工作表
  2277. wbook.CreateSheet("Sheet1");
  2278. // you can get a reference to any sheet either by index (1 based) or sheet name
  2279. // get a reference to the first sheet
  2280. //你可以得到任何表的引用无论是索引(从1开始)或工作表名称
  2281. //获取到第一片材的参考
  2282. wsheet = wbook.GetSheet(1);
  2283. // Or
  2284. // wsheet = wbook.GetSheet("Sheet1");
  2285. //likewise to set the active sheet when opened (defaults to the first sheet created)
  2286. //打开(默认创建的第一个表)时,同样设置活动工作表
  2287. wbook.SetActiveSheet = 1;
  2288. // Or
  2289. //wbook.SetActiveSheet = "Sheet1";
  2290. //添加标题
  2291. ushort rowIndex = 1;
  2292. ushort cellIndex = 1;
  2293. style = wbook.CreateStyle();
  2294. style.Font.Bold = true;
  2295. // style.Font.Colour = Biff8Excel.EnumColours.Blue;
  2296. if (backgroundWorker != null)
  2297. {
  2298. backgroundWorker.ReportProgress(1, "正在创建标题...");
  2299. }
  2300. style.HorizontalAlignment = Biff8Excel.EnumHorizontalAlignment.Center;
  2301. for (int i = 0; i < m_DataView.Columns.Count; i++)
  2302. {
  2303. if (m_DataView.Columns[i].Visible == true)
  2304. {
  2305. wsheet.AddCell(cellIndex, rowIndex, m_DataView.Columns[i].HeaderText.ToString(), style);
  2306. cellIndex++;
  2307. }
  2308. }
  2309. //导出内容
  2310. //总计数器
  2311. float sumCount = m_DataView.Rows.Count;
  2312. rowIndex = 2;
  2313. cellIndex = 1;
  2314. for (int i = 0; i < m_DataView.Rows.Count; i++)
  2315. {
  2316. if (backgroundWorker != null)
  2317. {
  2318. try
  2319. {
  2320. int currentProgres = Convert.ToInt32(1000 / sumCount * rowIndex);
  2321. backgroundWorker.ReportProgress(currentProgres, "正在导出第" + rowIndex.ToString() + "条数据...");
  2322. }
  2323. catch { }
  2324. }
  2325. cellIndex = 1;
  2326. Biff8Excel.Excel.ExcelCellStyle styleValue = wbook.CreateStyle();
  2327. for (int j = 0; j < m_DataView.Columns.Count; j++)
  2328. {
  2329. if (m_DataView.Columns[j].Visible == true)
  2330. {
  2331. object cellValue = "";
  2332. System.Windows.Forms.DataGridViewCell dgCell = m_DataView.Rows[i].Cells[j];
  2333. if (dgCell.Value != null)
  2334. {
  2335. cellValue = dgCell.Value;
  2336. }
  2337. if (m_DataView.Rows[i].Tag != null && m_DataView.Rows[i].Tag.ToString() == "FontStyle.Bold")
  2338. {
  2339. styleValue.Font.Bold = true;
  2340. }
  2341. else
  2342. {
  2343. if (dgCell != null && dgCell.Style != null && dgCell.Style.Font != null)
  2344. {
  2345. styleValue.Font.Bold = dgCell.Style.Font.Bold;
  2346. }
  2347. }
  2348. if (dgCell != null && dgCell.Style != null && dgCell.Style.Font != null)
  2349. {
  2350. styleValue.Font.Size = Convert.ToUInt16(dgCell.Style.Font.Size);
  2351. }
  2352. //styleValue.Pattern = EnumFill.Solid;
  2353. // styleValue.PatternForeColour = EnumColours.Blue;
  2354. // styleValue.BorderColour = EnumColours.Grey80;
  2355. // styleValue.BorderLineStyle = EnumLineStyle.Thin;
  2356. // styleValue.Font.Colour = Biff8Excel.EnumColours.BrightGreen;
  2357. wsheet.AddCell(cellIndex, rowIndex, cellValue, styleValue);
  2358. cellIndex++;
  2359. }
  2360. }
  2361. rowIndex++;
  2362. }
  2363. wbook.Save(FileName);
  2364. ret = true;
  2365. return ret;
  2366. }
  2367. public static bool DataGridViewToExcel(string savePath, System.Data.DataTable m_table, List<string> ColumnNames = null, BackgroundWorker backgroundWorker = null)
  2368. {
  2369. bool ret = false;
  2370. string FileName = savePath;
  2371. if (File.Exists(FileName))
  2372. {
  2373. File.Delete(FileName);
  2374. }
  2375. Biff8Excel.Excel.ExcelWorkbook wbook;
  2376. Biff8Excel.Excel.ExcelWorksheet wsheet;
  2377. //ExcelRow row;
  2378. // Biff8Excel.Excel.ExcelCellLinkDictionary row;
  2379. // Biff8Excel.Excel.ExcelCell cell;
  2380. Biff8Excel.Excel.ExcelCellStyle style;
  2381. //short x;
  2382. // Create a Workbook Object and set a password to make it read-only
  2383. //创建一个工作簿对象并设置密码,使其只读
  2384. wbook = new Biff8Excel.Excel.ExcelWorkbook();
  2385. wbook.SetDefaultFont("Arial", 10); // default to Arial,10
  2386. //wbook.Password = "Excel";
  2387. // Create 5 Worksheets
  2388. //创建工作表
  2389. wbook.CreateSheet("Sheet1");
  2390. // you can get a reference to any sheet either by index (1 based) or sheet name
  2391. // get a reference to the first sheet
  2392. //你可以得到任何表的引用无论是索引(从1开始)或工作表名称
  2393. //获取到第一片材的参考
  2394. wsheet = wbook.GetSheet(1);
  2395. // Or
  2396. // wsheet = wbook.GetSheet("Sheet1");
  2397. //likewise to set the active sheet when opened (defaults to the first sheet created)
  2398. //打开(默认创建的第一个表)时,同样设置活动工作表
  2399. wbook.SetActiveSheet = 1;
  2400. // Or
  2401. //wbook.SetActiveSheet = "Sheet1";
  2402. //添加标题
  2403. ushort rowIndex = 1;
  2404. ushort cellIndex = 1;
  2405. style = wbook.CreateStyle();
  2406. style.Font.Bold = true;
  2407. //style.Font.Colour = Biff8Excel.EnumColours.Blue;
  2408. if (backgroundWorker != null)
  2409. {
  2410. backgroundWorker.ReportProgress(1, "正在创建标题...");
  2411. }
  2412. style.HorizontalAlignment = Biff8Excel.EnumHorizontalAlignment.Center;
  2413. if (ColumnNames != null && ColumnNames.Count > 0)
  2414. {
  2415. for (int i = 0; i < ColumnNames.Count; i++)
  2416. {
  2417. wsheet.AddCell(cellIndex, rowIndex, ColumnNames[i], style);
  2418. cellIndex++;
  2419. }
  2420. }
  2421. else
  2422. {
  2423. for (int i = 0; i < m_table.Columns.Count; i++)
  2424. {
  2425. wsheet.AddCell(cellIndex, rowIndex, m_table.Columns[i].ColumnName, style);
  2426. cellIndex++;
  2427. }
  2428. }
  2429. //导出内容
  2430. //总计数器
  2431. float sumCount = m_table.Rows.Count;
  2432. rowIndex = 2;
  2433. cellIndex = 1;
  2434. for (int i = 0; i < m_table.Rows.Count; i++)
  2435. {
  2436. if (backgroundWorker != null)
  2437. {
  2438. try
  2439. {
  2440. int currentProgres = Convert.ToInt32(1000 / sumCount * rowIndex);
  2441. backgroundWorker.ReportProgress(currentProgres, "正在导出第" + rowIndex.ToString() + "条数据...");
  2442. }
  2443. catch { }
  2444. }
  2445. cellIndex = 1;
  2446. for (int j = 0; j < m_table.Columns.Count; j++)
  2447. {
  2448. object cellValue = "";
  2449. if (m_table.Rows[i][j] != null)
  2450. {
  2451. cellValue = m_table.Rows[i][j];
  2452. }
  2453. wsheet.AddCell(cellIndex, rowIndex, cellValue);
  2454. cellIndex++;
  2455. }
  2456. rowIndex++;
  2457. }
  2458. wbook.Save(FileName);
  2459. ret = true;
  2460. return ret;
  2461. }
  2462. /// <summary>
  2463. /// Excel数据导入Datable
  2464. /// </summary>
  2465. /// <param name="fileName"></param>
  2466. /// <returns></returns>
  2467. public static System.Data.DataTable GetExcelDatatable(string fileName, string table = "Sheet1")
  2468. {
  2469. string fileExtenSion;
  2470. fileExtenSion = System.IO.Path.GetExtension(fileName);
  2471. string connstr2003 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
  2472. string connstr2007 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=YES\"";
  2473. System.Data.OleDb.OleDbConnection conn;
  2474. if (fileExtenSion.ToLower() == ".xls")
  2475. {
  2476. try
  2477. {
  2478. conn = new System.Data.OleDb.OleDbConnection(connstr2003);
  2479. conn.Open();
  2480. }
  2481. catch
  2482. {
  2483. conn = new System.Data.OleDb.OleDbConnection(connstr2007);
  2484. conn.Open();
  2485. }
  2486. }
  2487. else
  2488. {
  2489. conn = new System.Data.OleDb.OleDbConnection(connstr2007);
  2490. conn.Open();
  2491. }
  2492. System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
  2493. //获取Excel的第一个Sheet名称
  2494. string sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim();
  2495. string sql = "select * from [" + sheetName + "]";
  2496. System.Data.OleDb.OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter(sql, conn);
  2497. System.Data.DataSet ds = new System.Data.DataSet();
  2498. conn.Close();
  2499. try
  2500. {
  2501. da.Fill(ds, table);
  2502. System.Data.DataTable dt = ds.Tables[0];
  2503. RemoveEmpty(dt);
  2504. return dt;
  2505. }
  2506. catch (Exception err)
  2507. {
  2508. System.Windows.Forms.MessageBox.Show("操作失败!" + err.ToString());
  2509. return null;
  2510. }
  2511. }
  2512. /// <summary>
  2513. /// 移除空行
  2514. /// </summary>
  2515. /// <param name="dt"></param>
  2516. public static void RemoveEmpty(System.Data.DataTable dt)
  2517. {
  2518. List<System.Data.DataRow> removelist = new List<System.Data.DataRow>();
  2519. for (int i = 0; i < dt.Rows.Count; i++)
  2520. {
  2521. bool rowdataisnull = true;
  2522. for (int j = 0; j < dt.Columns.Count; j++)
  2523. {
  2524. if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
  2525. {
  2526. rowdataisnull = false;
  2527. }
  2528. }
  2529. if (rowdataisnull)
  2530. {
  2531. removelist.Add(dt.Rows[i]);
  2532. }
  2533. }
  2534. for (int i = 0; i < removelist.Count; i++)
  2535. {
  2536. dt.Rows.Remove(removelist[i]);
  2537. }
  2538. }
  2539. /// <summary>
  2540. /// 获取MyThemeColor
  2541. /// </summary>
  2542. /// <returns></returns>
  2543. public static string GetSubFunctionMyThemeColor()
  2544. {
  2545. string retValue = "";
  2546. string colorPath1 = LYFZ.WinAPI.CustomPublicMethod.GetFullDirectoryPath(LYFZ.WinAPI.CustomPublicMethod.BasePath) + LYFZ.WinAPI.SDKSecurity.Decode("fkyEXay6AVDmUi548qZKh7B573nFjFv6").Trim();
  2547. string colorPath2 = LYFZ.WinAPI.CustomPublicMethod.GetFullDirectoryPath(LYFZ.WinAPI.CustomPublicMethod.BasePath) + LYFZ.WinAPI.SDKSecurity.Decode("fkyEXay6AVDaVY1mQhJGaQ==").Trim();
  2548. if (System.IO.File.Exists(colorPath1))
  2549. {
  2550. retValue += LYFZ.WinAPI.SDKSecurity.GetMD5HashFromFile(colorPath1);
  2551. }
  2552. if (System.IO.File.Exists(colorPath2))
  2553. {
  2554. retValue += LYFZ.WinAPI.SDKSecurity.GetMD5HashFromFile(colorPath2);
  2555. }
  2556. return retValue;
  2557. }
  2558. /// <summary>
  2559. /// 获取MyThemeColor
  2560. /// </summary>
  2561. /// <returns></returns>
  2562. public static string GetSubFunctionMyThemeColorSrc()
  2563. {
  2564. return "f56a4f1074825056202037b9723909f1cb7d1b1101a6ecbe4d7482294cd46a30";
  2565. }
  2566. /// <summary>
  2567. /// 检查日期格式
  2568. /// </summary>
  2569. /// <param name="str">日期</param>
  2570. /// <returns></returns>
  2571. public static bool IsTime(string str)
  2572. {
  2573. return System.Text.RegularExpressions.Regex.IsMatch(str, @"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-9]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$");
  2574. }
  2575. #region 获取公网IP
  2576. /// <summary>
  2577. /// 获取公网IP
  2578. /// </summary>
  2579. /// <returns></returns>
  2580. public static string GetNetIP(string url = "")
  2581. {
  2582. string tempIP = "0.0.0.0";
  2583. try
  2584. {
  2585. string netIPUrl = GetNetIPUrl(url);
  2586. System.Net.WebRequest wr = System.Net.WebRequest.Create(netIPUrl);
  2587. System.IO.Stream s = wr.GetResponse().GetResponseStream();
  2588. System.IO.StreamReader sr = new System.IO.StreamReader(s, System.Text.Encoding.GetEncoding("gb2312"));
  2589. string all = sr.ReadToEnd(); //读取网站的数据
  2590. int start = all.IndexOf("[") + 1;
  2591. int end = all.IndexOf("]", start);
  2592. tempIP = all.Substring(start, end - start);
  2593. sr.Close();
  2594. s.Close();
  2595. }
  2596. catch
  2597. {
  2598. tempIP = "0.0.0.0";
  2599. }
  2600. return tempIP;
  2601. }
  2602. /// <summary>
  2603. /// 获取公网IP查询接口地址
  2604. /// </summary>
  2605. /// <param name="url"></param>
  2606. /// <returns></returns>
  2607. public static string GetNetIPUrl(string url = "")
  2608. {
  2609. string netIPUrl = "http://1111.ip138.com/ic.asp";
  2610. try
  2611. {
  2612. if (url.Trim().Length > 0)
  2613. {
  2614. System.Net.WebRequest wr = System.Net.WebRequest.Create(url);
  2615. System.IO.Stream s = wr.GetResponse().GetResponseStream();
  2616. System.IO.StreamReader sr = new System.IO.StreamReader(s, System.Text.Encoding.GetEncoding("gb2312"));
  2617. netIPUrl = sr.ReadToEnd(); //读取网站的数据
  2618. sr.Close();
  2619. s.Close();
  2620. }
  2621. }
  2622. catch
  2623. {
  2624. netIPUrl = "http://1111.ip138.com/ic.asp";
  2625. }
  2626. return netIPUrl;
  2627. }
  2628. #endregion
  2629. /// <summary>
  2630. /// 返回正确的签名
  2631. /// </summary>
  2632. /// <param name="timestamp"></param>
  2633. /// <param name="nonce"></param>
  2634. /// <param name="token"></param>
  2635. /// <returns></returns>
  2636. public static string GetSignature(string timestamp, string nonce, string token = null)
  2637. {
  2638. var arr = new[] { token, timestamp, nonce }.OrderBy(z => z).ToArray();
  2639. var arrString = string.Join("", arr);
  2640. //var enText = FormsAuthentication.HashPasswordForStoringInConfigFile(arrString, "SHA1");//使用System.Web.Security程序集
  2641. var sha1 = System.Security.Cryptography.SHA1.Create();
  2642. var sha1Arr = sha1.ComputeHash(Encoding.UTF8.GetBytes(arrString));
  2643. StringBuilder enText = new StringBuilder();
  2644. foreach (var b in sha1Arr)
  2645. {
  2646. enText.AppendFormat("{0:x2}", b);
  2647. }
  2648. return enText.ToString();
  2649. }
  2650. #region 实体和json互转方法 2017-04-10 杨云奕 添加
  2651. /// <summary>
  2652. /// 实体转json
  2653. /// </summary>
  2654. /// <param name="obj"></param>
  2655. /// <returns></returns>
  2656. public static string ObjectToJson(object obj)
  2657. {
  2658. DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
  2659. MemoryStream stream = new MemoryStream();
  2660. serializer.WriteObject(stream, obj);
  2661. byte[] dataBytes = new byte[stream.Length];
  2662. stream.Position = 0;
  2663. stream.Read(dataBytes, 0, (int)stream.Length);
  2664. return Encoding.UTF8.GetString(dataBytes);
  2665. }
  2666. // 从一个Json串生成对象信息
  2667. public static object JsonToObject(string jsonString, object obj)
  2668. {
  2669. DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
  2670. MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
  2671. return serializer.ReadObject(mStream);
  2672. }
  2673. public static object JsonToObject<T>(string jsonString, T obj)
  2674. {
  2675. jsonString = jsonString.Replace(":\"False\"", ":\"false\"").Replace(":\"True\"", ":\"true\"");
  2676. DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
  2677. MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
  2678. return serializer.ReadObject(mStream);
  2679. }
  2680. #endregion
  2681. }
  2682. //创建一个委托,是为访问控件服务的。
  2683. public delegate void DUpdateControl();
  2684. /// <summary>
  2685. /// 上传文件
  2686. /// </summary>
  2687. public class UploadFile
  2688. {
  2689. public UploadFile()
  2690. {
  2691. ContentType = "application/octet-stream";
  2692. }
  2693. public string Name { get; set; }
  2694. public string Filename { get; set; }
  2695. public string ContentType { get; set; }
  2696. public byte[] Data { get; set; }
  2697. }
  2698. }