1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887 |
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Drawing;
- using System.ComponentModel; // 先添加该引用
- using System.IO;
- using System.Linq;
- using System.Drawing.Imaging;
- using System.Security.Cryptography.X509Certificates;
- using System.Net.Security;
- using System.Collections.Specialized;
- using System.Net;
- using Biff8Excel;
- using System.Runtime.Serialization.Json;
- namespace LYFZ.WinAPI
- {
- /// <summary>
- /// 自定义公共方法
- /// </summary>
- public class CustomPublicMethod
- {
- /// <summary>
- /// WebForm和WinForm通用的取当前根目录的方法
- /// </summary>
- public static string BasePath
- {
- get
- {
- System.Diagnostics.Process p = System.Diagnostics.Process.GetCurrentProcess();
- //WebDev.WebServer visual studio web server
- //xxx.vhost Winform
- //w3wp IIS7
- //aspnet_wp IIS6
- string processName = p.ProcessName.ToLower();
- string retPath = System.Windows.Forms.Application.StartupPath;
- if (processName == "aspnet_wp" || processName == "w3wp" || processName == "webdev.webserver" || processName == "iisexpress")
- {
- if (System.Web.HttpContext.Current != null)
- retPath = System.Web.HttpContext.Current.Server.MapPath("~/").TrimEnd(new char[] { '\\' });
- else //当控件在定时器的触发程序中使用时就为空
- {
- retPath = System.AppDomain.CurrentDomain.BaseDirectory.TrimEnd(new char[] { '\\' });
- }
- }
- return retPath;
- }
- }
- /// <summary>
- /// 转 20161003160647 (yyyyMMddHHmmss)格式long为时间类型
- /// </summary>
- /// <param name="dtString">20161003160647 (yyyyMMddHHmmss)格式long</param>
- /// <returns></returns>
- public static DateTime StringToDateTime(long dtLong)
- {
- return StringToDateTime(dtLong.ToString());
- }
- /// <summary>
- /// 转 20161003160647(yyyyMMddHHmmss) 格式字符串为时间类型
- /// </summary>
- /// <param name="dtString">20161003160647 (yyyyMMddHHmmss)格式字符串</param>
- /// <returns></returns>
- public static DateTime StringToDateTime(string dtString)
- {
- return Convert.ToDateTime(dtString.Insert(4, "-").Insert(7, "-").Insert(10, " ").Insert(13, ":").Insert(16, ":"));
- }
- /// <summary>
- /// 转DateTime 为 yyyyMMddHHmmss 格式的 long
- /// </summary>
- /// <param name="t"></param>
- /// <returns></returns>
- public static long DateTimeToLong(DateTime t)
- {
- return Convert.ToInt64(t.ToString("yyyyMMddHHmmss"));
- }
- /// <summary>
- /// 转Long格式:标准时间从1970年到现在的毫秒数
- /// </summary>
- /// <param name="dt"></param>
- /// <returns></returns>
- public static long ConvertDataTimeLong(DateTime dt)
- {
- DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
- TimeSpan toNow = dt.Subtract(dtStart);
- long timeStamp = toNow.Ticks;
- timeStamp = long.Parse(timeStamp.ToString().Substring(0, timeStamp.ToString().Length - 4));
- return timeStamp;
- }
- /// <summary>
- /// 转标准时间从1970年到现在的毫秒数 Long格式 为 DateTime
- /// </summary>
- /// <param name="d"></param>
- /// <returns></returns>
- public static DateTime ConvertLongDateTime(long d)
- {
- DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
- long lTime = long.Parse(d + "0000");
- TimeSpan toNow = new TimeSpan(lTime);
- DateTime dtResult = dtStart.Add(toNow);
- return dtResult;
- }
- static string _SpecialCharacters = "\\/:*?\"<>|";
- /// <summary>
- /// 特殊字符
- /// </summary>
- public static string SpecialCharacters
- {
- get { return CustomPublicMethod._SpecialCharacters; }
- }
- /// <summary>
- /// 检查指定字符串中是否存在特殊字符
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static bool IsSpecialCharacters(string str)
- {
- bool bl = false;
- char[] tempChars = str.ToCharArray();
- for (int i = 0; i < tempChars.Length; i++)
- {
- if (_SpecialCharacters.Contains(tempChars[i]))
- {
- bl = true;
- break;
- }
- }
- return bl;
- }
- /// <summary>
- /// 转换(过滤)特殊字符
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static string ConvertSpecialCharacter(string str)
- {
- return str.Replace(':', ':')
- .Replace('?', '?')
- .Replace('|', '|')
- .Replace('>', '>')
- .Replace('*', 'x')
- .Replace("\r", "")
- .Replace("\n", "")
- .Replace("\t", "");
- }
- /// <summary>
- /// 时间戳转为C#格式时间
- /// </summary>
- /// <param name="timeStamp"></param>
- /// <returns></returns>
- public static DateTime StampToDateTime(string timeStamp)
- {
- DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
- long lTime = long.Parse(timeStamp + "0000000");
- TimeSpan toNow = new TimeSpan(lTime);
- return dateTimeStart.Add(toNow);
- }
- /// <summary>
- /// DateTime时间格式转换为Unix时间戳格式
- /// </summary>
- /// <param name="time"></param>
- /// <returns></returns>
- public static int DateTimeToStamp(System.DateTime time)
- {
- System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
- return (int)(time - startTime).TotalSeconds;
- }
- /// <summary>
- /// 判断路径文件名指定的文件是否为 常用图片格式 jpg、jpge、png、bmp、tag、gif、
- /// </summary>
- /// <param name="fileName">路径文件名</param>
- /// <returns></returns>
- public static bool ExistsImgage(string fileName)
- {
- if (System.IO.Path.GetExtension(fileName).ToLower() == ".jpg".ToLower()
- || System.IO.Path.GetExtension(fileName).ToLower() == ".jpge"
- || System.IO.Path.GetExtension(fileName).ToLower() == ".png"
- || System.IO.Path.GetExtension(fileName).ToLower() == ".bmp"
- || System.IO.Path.GetExtension(fileName).ToLower() == ".tag"
- || System.IO.Path.GetExtension(fileName).ToLower() == ".gif")
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- /// <summary>
- /// C++ Dll 获取指定图片信息
- /// </summary>
- /// <param name="lpImgPath">要获取的指定的图片信息</param>
- /// <param name="dwWidth">ref 宽</param>
- /// <param name="dwHeight">ref 高</param>
- /// <param name="fHorizontal">ref 水平方向分辨率</param>
- /// <param name="fVertical">ref 垂直方向分辨率</param>
- /// <returns></returns>
- public static bool GetImgInfo(string lpImgPath, ref int dwWidth, ref int dwHeight, ref float fHorizontal, ref float fVertical)
- {
- try
- {
- bool ret = false;
- uint w = 0;
- uint h = 0;
- if (Environment.Is64BitProcess)
- {
- //64-bit
- ret = Win_X64.GetImgInfo(lpImgPath, ref w, ref h, ref fHorizontal, ref fVertical);
- }
- else
- {
- //估计很长一段时间内都是32-bit
- ret = Win_X86.GetImgInfo(lpImgPath, ref w, ref h, ref fHorizontal, ref fVertical);
- }
- dwWidth = Convert.ToInt32(w);
- dwHeight = Convert.ToInt32(h);
- return ret;
- }
- catch
- {
- return false;
- }
- }
- /// <summary>
- /// C++ Dll 生成缩略图
- /// </summary>
- /// <param name="lpImgPath">要生成的原图路径</param>
- /// <param name="lpNewImgPath">生成的缩略图要保存的路径</param>
- /// <param name="dwWidth">缩略图宽</param>
- /// <param name="dwHeight">缩略图高</param>
- /// <param name="dwQuality">0~100 品质 如果为 0 时无法控件品质 但可以使32位系统生成百兆以后相片的缩略图</param>
- /// <param name="isFullCut"> 是否为完整模式,按指定高宽增加画布空白或裁减尽可能的显示出最完整原图(不变形)</param>
- /// <returns></returns>
- public static bool GenerationImageThumbnail(string lpImgPath, string lpNewImgPath, int dwWidth, int dwHeight, int dwQuality, bool isFullCut = false)
- {
- try
- {
- bool ret = false;
- if (Environment.Is64BitProcess)
- {
- //64-bit
- ret = Win_X64.GenerationThumbnail(lpImgPath, lpNewImgPath, (uint)dwWidth, (uint)dwHeight, (uint)dwQuality);
- if (!ret)
- {
- ret = Win_X64.GenerationThumbnail(lpImgPath, lpNewImgPath, (uint)dwWidth, (uint)dwHeight, 0);
- }
- }
- else
- {
- //估计很长一段时间内都是32-bit
- ret = Win_X86.GenerationThumbnail(lpImgPath, lpNewImgPath, (uint)dwWidth, (uint)dwHeight, (uint)dwQuality);
- if (!ret)
- {
- ret = Win_X86.GenerationThumbnail(lpImgPath, lpNewImgPath, (uint)dwWidth, (uint)dwHeight, 0);
- }
- }
- if (ret && isFullCut)
- {
- Image image = Image.FromFile(lpNewImgPath);
- Bitmap result = new Bitmap(dwWidth, dwHeight);
- using (Graphics g = Graphics.FromImage(result))
- {
- Brush brush = Brushes.White;
- g.FillRectangle(brush, new Rectangle(new Point(0, 0), result.Size));
- g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
- g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
- g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
- g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
- g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
- g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
- g.Clear(Color.Transparent);
- //对齐方式
- 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);
- g.DrawImage(image, destRect, new RectangleF(new PointF(0F, 0F), image.Size), GraphicsUnit.Pixel);
- image.Dispose();
- image = null;
- }
- SaveIamge(result, 95, lpNewImgPath);
- }
- return ret;
- }
- catch
- {
- return false;
- }
- }
- /// <summary>
- /// 保存图片。
- /// </summary>
- /// <param name="image">要保存的图片</param>
- /// <param name="quality">品质(1L~100L之间,数值越大品质越好)</param>
- /// <param name="filename">保存路径</param>
- public static void SaveIamge(Bitmap image, long quality, string filename)
- {
- using (EncoderParameters encoderParams = new EncoderParameters(1))
- {
- using (EncoderParameter parameter = (encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality)))
- {
- ImageCodecInfo encoder = null;
- //取得扩展名
- string ext = Path.GetExtension(filename);
- if (string.IsNullOrEmpty(ext))
- ext = ".jpg";
- //根据扩展名得到解码、编码器
- foreach (ImageCodecInfo codecInfo in ImageCodecInfo.GetImageEncoders())
- {
- if (System.Text.RegularExpressions.Regex.IsMatch(codecInfo.FilenameExtension, string.Format(@"(;|^)\*\{0}(;|$)", ext), System.Text.RegularExpressions.RegexOptions.IgnoreCase))
- {
- encoder = codecInfo;
- break;
- }
- }
- string dirPath = Path.GetDirectoryName(filename);
- if (!Directory.Exists(dirPath))
- {
- Directory.CreateDirectory(dirPath);
- }
- if (System.IO.File.Exists(filename))
- {
- System.IO.File.Delete(filename);
- }
- image.Save(filename, encoder, encoderParams);
- image.Dispose();
- }
- }
- }
- /// <summary>
- /// 检查指定打印机名是否为有效的打印机
- /// </summary>
- /// <param name="printerName"></param>
- /// <returns></returns>
- public static bool CheckValidPrinter(string printerName)
- {
- System.Drawing.Printing.PrinterSettings myPrinter = new System.Drawing.Printing.PrinterSettings();
- myPrinter.PrinterName = printerName;//@"\\LIUCHAO-PC\Foxit Reader PDF Printer";
- return myPrinter.IsValid;
- }
- /// <summary>
- /// 程序执行时间测试
- /// </summary>
- /// <param name="dateBegin">开始时间</param>
- /// <param name="dateEnd">结束时间</param>
- /// <returns>返回(秒)单位,比如: 0.00239秒</returns>
- public static double ExecDateDiff(DateTime dateBegin, DateTime dateEnd)
- {
- TimeSpan ts1 = new TimeSpan(dateBegin.Ticks);
- TimeSpan ts2 = new TimeSpan(dateEnd.Ticks);
- TimeSpan ts3 = ts1.Subtract(ts2).Duration();
- //你想转的格式
- return ts3.TotalMilliseconds;
- }
- /// <summary>
- /// 释放并清除指定控件中的所以子控件
- /// </summary>
- /// <param name="_Control"></param>
- public static void DisposeControls(System.Windows.Forms.Control _Control)
- {
- try
- {
- foreach (System.Windows.Forms.Control c in _Control.Controls)
- {
- if (c.Controls.Count > 0)
- {
- DisposeControls(c);
- c.Controls.Clear();
- }
- c.Dispose();
- }
- _Control.Controls.Clear();
- }
- catch { }
- }
- /// <summary>
- /// 移除特殊符号
- /// </summary>
- /// <param name="fileName"></param>
- /// <returns></returns>
- public static string RemoveSpecialSymbol(string fileName)
- {
- return fileName.Replace(";", "");
- }
- /// <summary>
- /// 判断是否是IP地址格式 0.0.0.0
- /// </summary>
- /// <param name="str1">待判断的IP地址</param>
- /// <returns>true or false</returns>
- public static bool IsIPAddress(string str1)
- {
- if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;
- string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";
- System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(regformat, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
- return regex.IsMatch(str1);
- }
- /// <summary>
- /// 检查指定网络地址是否为内网地址
- /// </summary>
- /// <param name="networkAddress"></param>
- /// <returns></returns>
- public static bool CheckInternaNetworkAddress(string networkAddress)
- {
- bool ret = false;
- if (IsInnerIP(networkAddress) || networkAddress.Split('.').Length < 3)
- {
- ret = true;
- }
- return ret;
- }
- /// <summary>
- /// 判断IP地址是否为内网IP地址
- /// </summary>
- /// <param name="ipAddress">IP地址字符串</param>
- /// <returns></returns>
- public static bool IsInnerIP(string ipAddress)
- {
- bool isInnerIp = false;
- long ipNum = GetIpNum(ipAddress);
- /**
- 私有IP:A类 10.0.0.0-10.255.255.255
- B类 172.16.0.0-172.31.255.255
- C类 192.168.0.0-192.168.255.255
- 当然,还有127这个网段是环回地址
- **/
- long aBegin = GetIpNum("10.0.0.0");
- long aEnd = GetIpNum("10.255.255.255");
- long bBegin = GetIpNum("172.16.0.0");
- long bEnd = GetIpNum("172.31.255.255");
- long cBegin = GetIpNum("192.168.0.0");
- long cEnd = GetIpNum("192.168.255.255");
- isInnerIp = IsInner(ipNum, aBegin, aEnd) || IsInner(ipNum, bBegin, bEnd) || IsInner(ipNum, cBegin, cEnd) || ipAddress.Equals("127.0.0.1");
- return isInnerIp;
- }
- /// <summary>
- /// 把IP地址转换为Long型数字
- /// </summary>
- /// <param name="ipAddress">IP地址字符串</param>
- /// <returns></returns>
- public static long GetIpNum(string ipAddress)
- {
- try
- {
- String[] ip = ipAddress.Split('.');
- long a = int.Parse(ip[0]);
- long b = int.Parse(ip[1]);
- long c = int.Parse(ip[2]);
- long d = int.Parse(ip[3]);
- long ipNum = a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
- return ipNum;
- }
- catch
- {
- return 0;
- }
- }
- /// <summary>
- /// 判断用户IP地址转换为Long型后是否在内网IP地址所在范围
- /// </summary>
- /// <param name="userIp"></param>
- /// <param name="begin"></param>
- /// <param name="end"></param>
- /// <returns></returns>
- public static bool IsInner(long userIp, long begin, long end)
- {
- return (userIp >= begin) && (userIp <= end);
- }
- /// <summary>
- /// 全局ID GUID获取19位的唯一数字序列
- /// </summary>
- /// <returns></returns>
- public static long GenerateId()
- {
- byte[] buffer = Guid.NewGuid().ToByteArray();
- return BitConverter.ToInt64(buffer, 0);
- }
- /// <summary>
- /// 根据GUID获取32位的唯一字符串
- /// </summary>
- /// <param name=\"guid\"></param>
- /// <returns></returns>
- public static string GuidTo32String()
- {
- return Guid.NewGuid().ToString("n").ToUpper();
- }
- /// <summary>
- /// 根据GUID获取16位的唯一字符串
- /// </summary>
- /// <param name=\"guid\"></param>
- /// <returns></returns>
- public static string GuidTo16String()
- {
- long i = 1;
- foreach (byte b in Guid.NewGuid().ToByteArray())
- i *= ((int)b + 1);
- return string.Format("{0:x}", i - DateTime.Now.Ticks);
- }
- /// <summary>
- /// 生成22位唯一的数字 并发可用
- /// </summary>
- /// <returns></returns>
- public static string GenerateUniqueID()
- {
- System.Threading.Thread.Sleep(1); //保证yyyyMMddHHmmssffff唯一
- Random d = new Random(BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0));
- string strUnique = DateTime.Now.ToString("yyyyMMddHHmmssffff") + d.Next(1000, 9999);
- return strUnique;
- }
- //端口号的范围从0到65535
- /// <summary>
- /// 获取指定范围的随机端口号
- /// </summary>
- /// <param name="start">开始值</param>
- /// <param name="end">结束值</param>
- /// <returns></returns>
- public static int GetRandomPortNumber(int start = 0, int end = 65535)
- {
- if (start <= 0)
- {
- start = 0;
- }
- if (start > 65534)
- {
- start = 65534;
- }
- if (end <= 1)
- {
- end = 1;
- }
- if (end > 65535)
- {
- end = 65535;
- }
- return new Random().Next(start, end);
- }
- /// <summary>
- /// 26个大写英文字母
- /// </summary>
- 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' };
- /// <summary>
- /// 获取指定长度的随机字符串
- /// </summary>
- /// <param name="length">指定长度 最大长度为 64 个字符</param>
- /// <param name="isSpecialChar">是否含有特殊字符</param>
- /// <returns></returns>
- public static string GetSpecifyLengthRandomString(int length = 12, bool isSpecialChar = false)
- {
- if (length > 64)
- {
- length = 64;
- }
- Random ran = new Random();
- int RandKey = ran.Next(0, 25);
- string retString = CharArray[RandKey] + LYFZ.WinAPI.SDKSecurity.Encode(LYFZ.WinAPI.CustomPublicMethod.GenerateId().ToString()
- + LYFZ.WinAPI.CustomPublicMethod.GenerateId().ToString() + LYFZ.WinAPI.CustomPublicMethod.GenerateId().ToString());
- if (isSpecialChar)
- {
- retString = retString.Replace("==", "#Z").Replace("=", "&A").Replace("/", "@T").Replace("+", "&K");
- retString = retString.Insert(ran.Next(1, 10), "@");
- retString = retString.Insert(ran.Next(11, 20), "&");
- retString = retString.Insert(ran.Next(21, 32), "#");
- }
- else
- {
- retString = retString.Replace("==", "AZ").Replace("=", "A").Replace("/", "T").Replace("+", "K");
- }
- return retString.Substring(0, length);
- }
- /// <summary>
- /// 打开指定目录或文件
- /// </summary>
- /// <param name="arguments"></param>
- public static void OpenDirectory(string arguments)
- {
- if (System.IO.Directory.Exists(arguments))
- {
- System.Diagnostics.Process.Start(arguments);
- }
- else
- {
- LYFZ.WinAPI.CustomPublicMethod.RunStart("Explorer.exe", arguments);
- }
- }
- /// <summary>
- /// 运行外部应用程序
- /// </summary>
- /// <param name="path"></param>
- public static void RunStart(string path)
- {
- LYFZ.WinAPI.CustomPublicMethod.RunStart(path, "");
- }
- /// <summary>
- /// 运行外部应用程序
- /// </summary>
- /// <param name="path"></param>
- public static void RunStart(string path, string arguments = "")
- {
- try
- {
- if (System.IO.File.Exists(LYFZ.WinAPI.CustomPublicMethod.BasePath + path))
- {
- System.Diagnostics.Process.Start(LYFZ.WinAPI.CustomPublicMethod.BasePath + path, arguments);
- }
- else
- {
- System.Diagnostics.Process.Start(path, arguments);
- }
- }
- catch
- {
- }
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="dirPath"></param>
- /// <returns></returns>
- public static long GetDirectoryLength(string dirPath)
- {
- //判断给定的路径是否存在,如果不存在则退出
- if (!Directory.Exists(dirPath))
- return 0;
- long len = 0;
- //定义一个DirectoryInfo对象
- DirectoryInfo di = new DirectoryInfo(dirPath);
- //通过GetFiles方法,获取di目录中的所有文件的大小
- foreach (FileInfo fi in di.GetFiles())
- {
- len += fi.Length;
- }
- //获取di中所有的文件夹,并存到一个新的对象数组中,以进行递归
- DirectoryInfo[] dis = di.GetDirectories();
- if (dis.Length > 0)
- {
- for (int i = 0; i < dis.Length; i++)
- {
- len += GetDirectoryLength(dis[i].FullName);
- }
- }
- return len;
- }
- /// <summary>
- /// 获取文件夹中所有文件大小 单位 MB
- /// </summary>
- /// <param name="filePath"></param>
- /// <returns></returns>
- public static long GetMBDirectorySize(string dirPath)
- {
- return GetDirectoryLength(dirPath) / 1024 / 1024;
- }
- /// <summary>
- /// 获取文件集合中所有文件大小 单位 MB
- /// </summary>
- /// <param name="filePath"></param>
- /// <returns></returns>
- public static long GetMBFilesSize(string[] filesPaths)
- {
- long tempSize = 0;
- foreach (string filePath in filesPaths)
- {
- FileInfo fileInfo = new FileInfo(filePath);
- tempSize += fileInfo.Length;
- }
- return tempSize / 1024 / 1024;
- }
- /// <summary>
- /// 也是利用递归的思想,只不过是通过File类的Exits方法来判断
- /// 所给路径中所对应的是否为文件
- /// </summary>
- /// <param name="filePath"></param>
- /// <returns></returns>
- public static long FileSize(string filePath)
- {
- long temp = 0;
- //判断当前路径所指向的是否为文件
- if (File.Exists(filePath) == false)
- {
- string[] str1 = Directory.GetFileSystemEntries(filePath);
- foreach (string s1 in str1)
- {
- temp += FileSize(s1);
- }
- }
- else
- {
- //定义一个FileInfo对象,使之与filePath所指向的文件向关联,
- //以获取其大小
- FileInfo fileInfo = new FileInfo(filePath);
- return fileInfo.Length;
- }
- return temp;
- }
- /// <summary>
- /// 返回中文的星期几
- /// </summary>
- /// <param name="dayOfWeek"></param>
- /// <returns></returns>
- public static string GetDayOfWeek(DayOfWeek dayOfWeek)
- {
- string str = "";
- switch (dayOfWeek)
- {
- case DayOfWeek.Sunday: str = "星期日"; break;
- case DayOfWeek.Monday: str = "星期一"; break;
- case DayOfWeek.Tuesday: str = "星期二"; break;
- case DayOfWeek.Wednesday: str = "星期三"; break;
- case DayOfWeek.Thursday: str = "星期四"; break;
- case DayOfWeek.Friday: str = "星期五"; break;
- case DayOfWeek.Saturday: str = "星期六"; break;
- }
- return str;
- }
- /// <summary>
- /// 根据路径获取图片
- /// </summary>
- /// <param name="imgaPath">程序运行当前根目录下的Resources资源文件夹路径 如:\\ToolsMenu\\payments.png</param>
- /// <returns></returns>
- public static System.Drawing.Image GetMenuItemImage(string imgaPath)
- {
- System.Drawing.Image retimage = null;
- if (imgaPath != "")
- {
- try
- {
- string tempPath = CustomPublicMethod.BasePath + "\\Resources" + imgaPath;
- // System.Drawing.Image image = new System.Drawing.Bitmap(tempPath);
- retimage = (System.Drawing.Image)GetPathToBitmap(tempPath);
- // image.Dispose();
- }
- catch
- {
- }
- }
- return retimage;
- }
- /// <summary>
- /// 根据路径获取图片
- /// </summary>
- /// <param name="imgaPath"></param>
- /// <returns></returns>
- public static System.Drawing.Bitmap GetPathToBitmap(string imgaPath)
- {
- try
- {
- FileStream fs = new FileStream(imgaPath, FileMode.Open, FileAccess.Read);
- Bitmap bmp = new Bitmap(fs);
- Bitmap retbmp = new Bitmap(bmp);
- fs.Close();
- fs.Dispose();
- bmp.Dispose();
- bmp = null;
- return retbmp;
- }
- catch { return null; }
- }
- #region 获取灰色图像
- /// <summary>
- /// 获取灰色图像
- /// </summary>
- /// <returns></returns>
- public static Image GetGrayImage(Image image)
- {
- return CustomPublicMethod.GetGrayImage(new Bitmap(image));
- }
- /// <summary>
- /// 获取灰色图像
- /// </summary>
- /// <returns></returns>
- public static Bitmap GetGrayImage(Bitmap image)
- {
- int Height = image.Height;
- int Width = image.Width;
- Bitmap bitmap = image;
- Bitmap MyBitmap = new Bitmap(image);
- //使用左上角的一点的颜色作为我们透明色
- Color colorTransparent = MyBitmap.GetPixel(0, 0);
- Color pixel;
- for (int x = 0; x < Width; x++)
- {
- for (int y = 0; y < Height; y++)
- {
- pixel = MyBitmap.GetPixel(x, y);
- if (pixel != colorTransparent)
- {
- int r, g, b, Result = 0;
- r = pixel.R;
- g = pixel.G;
- b = pixel.B;
- //实例程序以加权平均值法产生黑白图像
- int iType = 2;
- switch (iType)
- {
- case 0://平均值法
- Result = ((r + g + b) / 3);
- break;
- case 1://最大值法
- Result = r > g ? r : g;
- Result = Result > b ? Result : b;
- break;
- case 2://加权平均值法
- Result = ((int)(0.7 * r) + (int)(0.2 * g) + (int)(0.1 * b));
- break;
- }
- bitmap.SetPixel(x, y, Color.FromArgb(Result, Result, Result));
- }
- }
- }
- MyBitmap.Dispose();
- return bitmap;
- }
- #endregion
- /// <summary>
- /// 返回指定类型是否为允许为null的 Nullable泛型对象
- /// </summary>
- /// <param name="_type"></param>
- /// <returns>是Nullable泛型对象为 true 否则为 false</returns>
- public static bool IsNullable(Type _type)
- {
- bool bl = _type.Name.ToLower().Contains("Nullable".ToLower());
- return bl;
- }
- /// <summary>
- /// 验证一个类的完全限定名中是否以“system.”开头
- /// </summary>
- /// <param name="classFullName"></param>
- /// <returns>以“system.”开头为 true 否则为 false </returns>
- public static bool VerificationClassFullNameIsSystem(string classFullName)
- {
- bool bl = false;
- if (classFullName.ToLower().IndexOf("system.") == 0)
- {
- bl = true;
- }
- return bl;
- }
- /// <summary>
- /// 获取实例对象属性的值
- /// </summary>
- /// <param name="model">实例对象</param>
- /// <param name="propertyName">属性名</param>
- /// <returns></returns>
- public static object GetPropertyValue(object model, string propertyName)
- {
- System.Reflection.PropertyInfo propertyInfo = model.GetType().GetProperty(propertyName);
- if (propertyInfo != null)
- {
- object tempValue = propertyInfo.GetValue(model, null);//对应字段值
- return tempValue;
- }
- else
- {
- return null;
- }
- }
- /// <summary>
- /// 设置实例对象属性的值
- /// </summary>
- /// <param name="model">实例对象</param>
- /// <param name="propertyInfo">属性对象</param>
- /// <param name="value">要设置的值</param>
- public static void SetPropertyValue(object model, System.Reflection.PropertyInfo propertyInfo, object value)
- {
- if (propertyInfo == null)
- {
- return;
- }
- Type tempType = propertyInfo.PropertyType;
- if (IsNullable(tempType))
- {
- tempType = Nullable.GetUnderlyingType(propertyInfo.PropertyType);
- }
- object tempValue = value;
- if (tempValue == null)
- {
- try
- {
- propertyInfo.SetValue(model, null, null);
- }
- catch { }
- }
- else
- {
- switch (tempType.Name)
- {
- // 空引用。
- case "Empty":
- propertyInfo.SetValue(model, tempValue.ToString(), null);
- break;
- // 常规类型,表示不会由另一个 TypeCode 显式表示的任何引用或值类型。
- case "Object":
- propertyInfo.SetValue(model, tempValue, null);
- break;
- // 数据库空(列)值。
- case "DBNull":
- propertyInfo.SetValue(model, null, null);
- break;
- // 简单类型,表示 true 或 false 的布尔值。
- case "Boolean":
- try
- {
- propertyInfo.SetValue(model, Convert.ToBoolean(tempValue), null);
- }
- catch
- {
- propertyInfo.SetValue(model, false, null);
- }
- break;
- //字符
- case "Char":
- propertyInfo.SetValue(model, Convert.ToChar(tempValue), null);
- break;
- // 整型,表示值介于 -128 到 127 之间的有符号 8 位整数。
- case "SByte":
- propertyInfo.SetValue(model, Convert.ToSByte(tempValue), null);
- break;
- // 0 and 255.
- case "Byte":
- propertyInfo.SetValue(model, Convert.ToByte(tempValue), null);
- break;
- // 整型,表示值介于 -32768 到 32767 之间的有符号 16 位整数。
- case "Int16":
- propertyInfo.SetValue(model, Convert.ToInt16(tempValue), null);
- break;
- // 整型,表示值介于 0 到 65535 之间的无符号 16 位整数。
- case "UInt16":
- propertyInfo.SetValue(model, Convert.ToUInt16(tempValue), null);
- break;
- // 整型,表示值介于 -2147483648 到 2147483647 之间的有符号 32 位整数。
- case "Int32":
- try
- {
- propertyInfo.SetValue(model, Convert.ToInt32(tempValue), null);
- }
- catch
- {
- propertyInfo.SetValue(model, Convert.ToInt32(0), null);
- }
- break;
- // 整型,表示值介于 0 到 4294967295 之间的无符号 32 位整数。
- case "UInt32":
- propertyInfo.SetValue(model, Convert.ToUInt32(tempValue), null);
- break;
- // 整型,表示值介于 -9223372036854775808 到 9223372036854775807 之间的有符号 64 位整数。
- case "Int64":
- propertyInfo.SetValue(model, Convert.ToInt64(tempValue), null);
- break;
- // 整型,表示值介于 0 到 18446744073709551615 之间的无符号 64 位整数。
- case "UInt64":
- propertyInfo.SetValue(model, Convert.ToUInt64(tempValue), null);
- break;
- // 浮点型,表示从大约 1.5 x 10 -45 到 3.4 x 10 38 且精度为 7 位的值。
- case "Single":
- propertyInfo.SetValue(model, Convert.ToSingle(tempValue), null);
- break;
- // 浮点型,表示从大约 5.0 x 10 -324 到 1.7 x 10 308 且精度为 15 到 16 位的值。
- case "Double":
- try
- {
- propertyInfo.SetValue(model, Convert.ToDouble(tempValue), null);
- }
- catch
- {
- propertyInfo.SetValue(model, 0, null);
- }
- break;
- // 简单类型,表示从 1.0 x 10 -28 到大约 7.9 x 10 28 且有效位数为 28 到 29 位的值。
- case "Decimal":
- propertyInfo.SetValue(model, Convert.ToDecimal(tempValue), null);
- break;
- // 表示一个日期和时间值的类型。
- case "DateTime":
- try
- {
- propertyInfo.SetValue(model, Convert.ToDateTime(tempValue), null);
- }
- catch
- {
- // propertyInfo.SetValue(model, Convert.ToDateTime("1753-01-01"), null);
- }
- break;
- // 密封类类型,表示 Unicode 字符串。
- case "String":
- propertyInfo.SetValue(model, tempValue.ToString(), null);
- break;
- default:
- string classFullName = tempType.ToString();
- if (!VerificationClassFullNameIsSystem(classFullName))
- {
- try
- {
- Type valueType = tempType.Module.Assembly.GetType(classFullName);
- // object obj = Activator.CreateInstance(type, null);
- tempValue = Activator.CreateInstance(valueType, new object[] { tempValue.ToString() });
- }
- catch { }
- }
- propertyInfo.SetValue(model, tempValue, null);
- break;
- }
- }
- }
- /// <summary>
- /// 设置实例对象属性的值
- /// </summary>
- /// <param name="model">实例对象</param>
- /// <param name="propertyName">属性名</param>
- /// <param name="value">要设置的值</param>
- public static void SetPropertyValue(object model, string propertyName, object value)
- {
- // Type tempType = model.GetType().GetProperty(propertyName).PropertyType;
- System.Reflection.PropertyInfo propertyInfo = model.GetType().GetProperty(propertyName);
- if (propertyInfo != null)
- {
- SetPropertyValue(model, propertyInfo, value);
- }
- }
- /// <summary>
- /// 获取枚举描述
- /// </summary>
- /// <param name="e"></param>
- /// <returns></returns>
- public static string ConvertEnumToDescription(object e)
- {
- System.Reflection.FieldInfo EnumInfo = e.GetType().GetField(e.ToString());
- DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])EnumInfo.
- GetCustomAttributes(typeof(DescriptionAttribute), false);
- if (EnumAttributes.Length > 0)
- {
- return EnumAttributes[0].Description;
- }
- return e.ToString();
- }
- /// <summary>
- /// 获取完整的文件夹目录
- /// </summary>
- /// <param name="directoryPath"></param>
- /// <returns></returns>
- public static string GetDirectoryPath(string directoryPath)
- {
- if (directoryPath.LastIndexOf(System.IO.Path.DirectorySeparatorChar) != directoryPath.Length - 1)
- {
- directoryPath = directoryPath + System.IO.Path.DirectorySeparatorChar;
- }
- return directoryPath;
- }
- public static void SetColumnDisplayIndex(int index, string columnDisplayString, System.Windows.Forms.DataGridViewColumnCollection columns)
- {
- if (columnDisplayString.Trim() != "")
- {
- string[] columnDisplays = columnDisplayString.Split('|');
- for (int i = 0; i < columnDisplays.Length; i++)
- {
- string[] columnDisplayValues = columnDisplays[i].Split(':');
- string columnName = columnDisplayValues[0];
- int displayIndex = 0;
- try
- {
- displayIndex = Convert.ToInt32(columnDisplayValues[1]);
- }
- catch { }
- bool isDisplay = true;
- try
- {
- isDisplay = Convert.ToBoolean(columnDisplayValues[2]);
- }
- catch { }
- int columnWidth = 100;
- try
- {
- columnWidth = Convert.ToInt32(columnDisplayValues[3]);
- }
- catch { }
- if (displayIndex == index)
- {
- try
- {
- System.Windows.Forms.DataGridViewColumn column = columns[columnName];
- column.DisplayIndex = displayIndex;
- column.Width = columnWidth;
- column.Visible = isDisplay;
- }
- catch { }
- break;
- }
- }
- }
- }
- /// <summary>
- /// 设置列标题顺序
- /// </summary>
- /// <param name="columnDisplayString"></param>
- /// <param name="column"></param>
- public static void SetColumnDisplayIndex(string columnDisplayString, System.Windows.Forms.DataGridViewColumnCollection columns, System.Windows.Forms.ContextMenuStrip cmsGridViewDisplayMenu = null, string hiddenFields = "")
- {
- if (columnDisplayString == null)
- {
- columnDisplayString = "";
- }
- if (cmsGridViewDisplayMenu != null)
- {
- cmsGridViewDisplayMenu.Items.Clear();
- }
- for (int i = 0; i < columns.Count; i++)
- {
- SetColumnDisplayIndex(i, columnDisplayString, columns);
- }
- for (int i = 0; i < columns.Count; i++)
- {
- System.Windows.Forms.DataGridViewColumn column = columns[i];
- if (!("," + hiddenFields.ToLower() + ",").Contains("," + column.Name.ToLower() + ","))
- {
- SetToolStripMenuItem(column, cmsGridViewDisplayMenu);
- }
- else
- {
- column.Visible = false;
- }
- }
- }
- // static string tempstr = "";
- /// <summary>
- /// 设置标题菜单项
- /// </summary>
- /// <param name="columnDisplayString"></param>
- /// <param name="column"></param>
- public static void SetToolStripMenuItem(System.Windows.Forms.DataGridViewColumn column, System.Windows.Forms.ContextMenuStrip cmsGridViewDisplayMenu = null)
- {
- bool isDisplay = column.Visible;
- if (cmsGridViewDisplayMenu != null)
- {
- System.Windows.Forms.ToolStripMenuItem item = new System.Windows.Forms.ToolStripMenuItem();
- item.Text = column.HeaderText;
- item.Checked = isDisplay;
- if (cmsGridViewDisplayMenu.Items.Count < 2)
- {
- item.Enabled = false;
- }
- if (column.HeaderText.ToLower() == "id")
- {
- item.Enabled = false;
- }
- cmsGridViewDisplayMenu.Items.Add(item);
- column.HeaderCell.ContextMenuStrip = cmsGridViewDisplayMenu;
- }
- }
- /// <summary>
- /// 获取ColumnDisplayString列标题顺序字符串
- /// </summary>
- /// <param name="columns"></param>
- /// <returns></returns>
- public static string GetColumnDisplayString(System.Windows.Forms.DataGridViewColumnCollection columns)
- {
- string tempValue = "";
- for (int i = 0; i < columns.Count; i++)
- {
- System.Windows.Forms.DataGridViewColumn column = columns[i];
- tempValue += column.Name + ":" + column.DisplayIndex + ":" + column.Visible.ToString() + ":" + column.Width + "|";
- }
- return tempValue;
- }
- /// <summary>
- /// 获取DataGridView唯一标识
- /// </summary>
- /// <param name="frmName"></param>
- /// <param name="dataGridViewName"></param>
- /// <returns></returns>
- public static string GetDataGridViewUniquelyIdentify(string frmName, string dataGridViewName)
- {
- return frmName + "_" + dataGridViewName;
- }
- #region Web GET POST方式提交
- static System.Net.SecurityProtocolType _HTTP_SecurityProtocolType = System.Net.SecurityProtocolType.Ssl3;
- /// <summary>
- /// Http 方式SSL安全协议
- /// </summary>
- public static System.Net.SecurityProtocolType HTTP_SecurityProtocolType
- {
- get { return CustomPublicMethod._HTTP_SecurityProtocolType; }
- set { CustomPublicMethod._HTTP_SecurityProtocolType = value; }
- }
- static System.Net.SecurityProtocolType _HTTPS_SecurityProtocolType = System.Net.SecurityProtocolType.Tls;
- /// <summary>
- /// Https 方式SSL安全协议
- /// </summary>
- public static System.Net.SecurityProtocolType HTTPS_SecurityProtocolType
- {
- get { return CustomPublicMethod._HTTPS_SecurityProtocolType; }
- set { CustomPublicMethod._HTTPS_SecurityProtocolType = value; }
- }
- public static void SetServicePointManagerSecurityProtocol(string url)
- {
- //这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
- System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
- if (url.ToLower().StartsWith("https"))
- {
- System.Net.ServicePointManager.SecurityProtocol = _HTTPS_SecurityProtocolType;
- }
- else
- {
- System.Net.ServicePointManager.SecurityProtocol = _HTTP_SecurityProtocolType;
- }
- }
- //回调验证证书问题
- public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
- {
- // 总是接受
- return true;
- }
- /// <summary>
- /// 以Post 形式提交表单数据到 uri
- /// </summary>
- /// <param name="uri"></param>
- /// <param name="files"></param>
- /// <param name="values"></param>
- /// <returns></returns>
- public static string FormOrDataPost(string url, IEnumerable<UploadFile> files, NameValueCollection values, Encoding _Encoding = null)
- {
- System.GC.Collect();
- if (_Encoding == null)
- {
- _Encoding = Encoding.Default;
- }
- string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
- request.ContentType = "multipart/form-data; boundary=" + boundary;
- request.Method = "POST";
- request.KeepAlive = true;
- request.Credentials = CredentialCache.DefaultCredentials;
- Stream requestStream = request.GetRequestStream();
- //MemoryStream stream = new MemoryStream();
- byte[] line = _Encoding.GetBytes("\r\n--" + boundary + "\r\n");
- //提交文本字段
- if (values != null)
- {
- string format = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
- foreach (string key in values.Keys)
- {
- string s = string.Format(format, key, values[key]);
- byte[] data = Encoding.UTF8.GetBytes(s);
- requestStream.Write(data, 0, data.Length);
- }
- requestStream.Write(line, 0, line.Length);
- }
- //提交文件
- if (files != null)
- {
- string fformat = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
- foreach (UploadFile file in files)
- {
- string s = string.Format(fformat, file.Name, file.Filename);
- byte[] data = Encoding.UTF8.GetBytes(s);
- requestStream.Write(data, 0, data.Length);
- byte[] filedata = file.Data;
- if (file.Data != null)
- {
- requestStream.Write(file.Data, 0, file.Data.Length);
- }
- else
- {
- filedata = File.ReadAllBytes(file.Filename);
- requestStream.Write(filedata, 0, filedata.Length);
- }
- requestStream.Write(line, 0, line.Length);
- filedata = null;
- }
- }
- // request.ContentLength = requestStream.Length;
- requestStream.Close();
- requestStream = null;
- using (System.Net.WebResponse wr = request.GetResponse())
- {
- System.IO.StreamReader str = new System.IO.StreamReader(wr.GetResponseStream(), _Encoding);
- string strMsg = str.ReadToEnd();
- str.Close();
- str.Dispose();
- str = null;
- request.Abort();
- request = null;
- strMsg = System.Web.HttpUtility.UrlDecode(strMsg);
- return strMsg;
- //在这里对接收到的页面内容进行处理
- }
- }
- /// <summary>
- /// Web POST方式提交
- /// </summary>
- /// <param name="url"></param>
- /// <param name="postData"></param>
- /// <param name="_Encoding">字符编码</param>
- /// <param name="_ContentType"> Content-typeHTTP 标头的值</param>
- /// <returns></returns>
- public static string HttpWebRequestPOST(string url, string postData, Encoding _Encoding = null, string _ContentType = "application/x-www-form-urlencoded", CookieContainer myCookieContainer = null, bool isUrlDecode = true)
- {
- try
- {
- //string postData = "CustomerID=LYFZTYUF"
- // + "&ShareTitle=" + System.Web.HttpUtility.UrlEncode("OK!Test")
- // + "&ShareDescription=" + System.Web.HttpUtility.UrlEncode("利亚方舟微相册分享体验微 信号:340508706@qq.com");
- System.GC.Collect();
- if (_Encoding == null)
- {
- _Encoding = Encoding.Default;
- }
- byte[] byteArray = _Encoding.GetBytes(postData);
- if (System.Net.ServicePointManager.DefaultConnectionLimit < 512)
- {
- System.Net.ServicePointManager.DefaultConnectionLimit = 512;
- }
- //这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。
- // System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
- SetServicePointManagerSecurityProtocol(url);
- // string url = "http://localhost:8000/webService/POSTText?t=" + DateTime.Now.ToString("yyyyMMddhhmmss"); //POST到网站
- System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new Uri(url));
- // System.Net.CookieContainer cookies = new System.Net.CookieContainer();
- // webRequest.CookieContainer=cookies;
- 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, */*";
- 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)";
- webRequest.KeepAlive = false;
- webRequest.ProtocolVersion = System.Net.HttpVersion.Version10;
- webRequest.Method = "POST";
- webRequest.ContentType = _ContentType;//"application/x-www-form-urlencoded";
- webRequest.ContentLength = byteArray.Length;
- if (myCookieContainer != null)
- {
- webRequest.CookieContainer = myCookieContainer;
- }
- System.IO.Stream newStream = webRequest.GetRequestStream();
- newStream.Write(byteArray, 0, byteArray.Length);
- newStream.Close();
- newStream = null;
- //接收返回信息:
- webRequest.Timeout = 600000;
- System.Threading.Thread.Sleep(10);
- using (System.Net.WebResponse wr = webRequest.GetResponse())
- {
- System.IO.StreamReader str = new System.IO.StreamReader(wr.GetResponseStream(), _Encoding);
- string strMsg = str.ReadToEnd();
- str.Close();
- str.Dispose();
- str = null;
- webRequest.Abort();
- webRequest = null;
- if (isUrlDecode)
- {
- strMsg = System.Web.HttpUtility.UrlDecode(strMsg);
- }
- return strMsg;
- //在这里对接收到的页面内容进行处理
- }
- // System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)webRequest.GetResponse();
- //cookies = (System.Net.CookieContainer)response.Cookies;
- //System.Net.Cookie cookie = new System.Net.Cookie();
- // System.Net.Cookie cookie = response.Cookies[0];
- // System.Net.CookieCollection ck = cookies.GetCookies(webRequest.RequestUri);
- /* System.IO.StreamReader stream = new System.IO.StreamReader(response.GetResponseStream(), Encoding.Default);
- string Message = stream.ReadToEnd();
- Message = System.Web.HttpUtility.UrlDecode(Message);
- stream.Close();
- response.Close();
- webRequest.Abort();
- return Message;*/
- }
- catch (Exception ex)
- {
- try
- {
- return HttpContentPOST(url, postData);
- }
- catch
- {
- System.Net.ServicePointManager.Expect100Continue = false;
- return "Request failed,Exception:" + ex.Message;
- }
- }
- }
- // string postData = "";
- // System.Net.Http.HttpContent content = new System.Net.Http.StringContent(postData);
- //var result = client.PostAsync(url, content).Result;
- /// <summary>
- /// Web HttpClient GET方式提交
- /// </summary>
- /// <param name="url"></param>
- /// <param name="_Encoding"></param>
- /// <returns></returns>
- public static string HttpContentGET(string url, Encoding _Encoding = null)
- {
- string resultStr = "";
- SetServicePointManagerSecurityProtocol(url);
- System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
- var result = client.GetAsync(url).Result;
- resultStr = result.Content.ReadAsStringAsync().Result;
- client.Dispose();
- return System.Web.HttpUtility.UrlDecode(resultStr);
- }
- /// <summary>
- /// Web HttpClient POST方式提交
- /// </summary>
- /// <param name="url"></param>
- /// <param name="postData"></param>
- /// <param name="_Encoding"></param>
- /// <returns></returns>
- public static string HttpContentPOST(string url, string postData, Encoding _Encoding = null)
- {
- string resultStr = "";
- SetServicePointManagerSecurityProtocol(url);
- System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
- System.Net.Http.HttpContent content = new System.Net.Http.StringContent(postData);
- var result = client.PostAsync(url, content).Result;
- resultStr = result.Content.ReadAsStringAsync().Result;
- client.Dispose();
- return System.Web.HttpUtility.UrlDecode(resultStr);
- }
- /// <summary>
- /// Web GET方式提交
- /// </summary>
- /// <param name="url"></param>
- /// <param name="_Encoding">字符编码</param>
- /// <returns></returns>
- public static string HttpWebRequestGET(string url, Encoding _Encoding = null, CookieContainer myCookieContainer = null, bool isUrlDecode = true, string _ContentType = null)
- {
- try
- {
- System.GC.Collect();
- if (_Encoding == null)
- {
- _Encoding = Encoding.Default;
- }
- // Random random = new Random();
- // string url = "http://192.168.1.141:8000/webService/getuserinfo?account=111111&password=1234&t="+ DateTime.Now.ToString("yyyyMMddhhmmss");
- if (System.Net.ServicePointManager.DefaultConnectionLimit < 512)
- {
- System.Net.ServicePointManager.DefaultConnectionLimit = 512;
- }
- SetServicePointManagerSecurityProtocol(url);
- System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
- 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,*/*";
- 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)";
- webRequest.Method = "GET";
- webRequest.Timeout = 600000;
- webRequest.KeepAlive = false;
- webRequest.ProtocolVersion = System.Net.HttpVersion.Version10;
- if (_ContentType != null)
- {
- webRequest.ContentType = _ContentType;
- }
- if (myCookieContainer != null)
- {
- webRequest.CookieContainer = myCookieContainer;
- }
- System.Threading.Thread.Sleep(5);
- using (System.Net.WebResponse wr = webRequest.GetResponse())
- {
- System.IO.StreamReader str = new System.IO.StreamReader(wr.GetResponseStream(), _Encoding);
- string strMsg = str.ReadToEnd();
- str.Close();
- str.Dispose();
- str = null;
- webRequest.Abort();
- webRequest = null;
- if (isUrlDecode)
- {
- strMsg = System.Web.HttpUtility.UrlDecode(strMsg);
- }
- return strMsg;
- //在这里对接收到的页面内容进行处理
- }
- // System.Net.HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse();
- // System.IO.Stream imgStream = webResponse.GetResponseStream();
- // System.IO.StreamReader stream = new System.IO.StreamReader(imgStream, Encoding.Default);
- // string Message = stream.ReadToEnd();
- // Message = System.Web.HttpUtility.UrlDecode(Message);
- // stream.Close();
- // webResponse.Close();
- // webRequest.Abort();
- // return Message;
- }
- catch (Exception ex)
- {
- try
- {
- return HttpContentGET(url);
- }
- catch
- {
- System.Net.ServicePointManager.Expect100Continue = false;
- return "Request failed,Exception:" + ex.Message;
- }
- }
- }
- /// <summary>
- /// 获取Http网络图片
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- public static Image GetHttpWebRequestImage(string url)
- {
- System.IO.Stream imgStream = System.Net.WebRequest.Create(url).GetResponse().GetResponseStream();
- Image obj = Image.FromStream(imgStream);
- Image retobj = (Image)obj.Clone();
- imgStream.Close();
- imgStream.Dispose();
- imgStream = null;
- obj.Dispose();
- obj = null;
- return retobj;
- }
- /// <summary>
- /// 获取Http网络图片
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- public static Bitmap GetHttpWebRequestBitmap(string url)
- {
- System.IO.Stream imgStream = (new System.Net.WebClient()).OpenRead(url);
- Bitmap obj = new Bitmap(imgStream);
- Bitmap retobj = (Bitmap)obj.Clone();
- imgStream.Close();
- imgStream.Dispose();
- imgStream = null;
- obj.Dispose();
- obj = null;
- return retobj;
- }
- #endregion
- #region 短信发送相关方法
- /// <summary>
- /// 验证手机号 返回空值时为验证通过, 如果有错误格式手机号时返回错误手机号字符串
- /// </summary>
- /// <param name="phoneStr">要验证的手机字符串,多个手机号以“,”号分隔</param>
- /// <returns>返回空值时为验证通过,如果有错误格式手机号时返回错误手机号字符串</returns>
- public static string ValidationPhones(string phoneStr)
- {
- string tempLawfulPhone = "";
- return ValidationPhones(phoneStr, ref tempLawfulPhone);
- }
- static List<string> _FilterMobileNumberList = new List<string>();
- /// <summary>
- /// 要过虑的手机号集合
- /// </summary>
- public static List<string> FilterMobileNumberList
- {
- get { return CustomPublicMethod._FilterMobileNumberList; }
- set { CustomPublicMethod._FilterMobileNumberList = value; }
- }
- /// <summary>
- /// 验证手机号 返回空值时为验证通过, 如果有错误格式手机号时返回错误手机号字符串
- /// </summary>
- /// <param name="phoneStr">要验证的手机字符串,多个手机号以“,”号分隔</param>
- /// <param name="lawfulPhone">返回正确的手机号</param>
- /// <returns>返回空值时为验证通过,如果有错误格式手机号时返回错误手机号字符串</returns>
- public static string ValidationPhones(string phoneStr, ref string lawfulPhone)
- {
- string ErrorPhone = "";
- string CorrectPhone = "";//有效手机号
- string[] phones = phoneStr.Trim().Split(',');
- if (phoneStr.Length < 11)
- {
- ErrorPhone += phoneStr;
- }
- else
- {
- lawfulPhone = "";
- foreach (string phone in phones)
- {
- if (phone.Trim().Length > 0)
- {
- long phoneDigital = 0;
- if (phone.IndexOf("1") == 0 && phone.Length == 11 && long.TryParse(phone, out phoneDigital) && !FilterMobileNumberList.Contains(phone))
- {
- if (phone.IndexOf("11") == 0 || phone.IndexOf("12") == 0)
- {
- ErrorPhone += phone + ",";
- }
- else
- {
- if (!lawfulPhone.Contains(phone))
- {
- CorrectPhone += phone;
- lawfulPhone += phone + ",";
- }
- }
- }
- else
- {
- ErrorPhone += phone + ",";
- }
- }
- }
- }
- //去除结尾多余的“,”
- if (lawfulPhone.Length >= 11)
- {
- if (lawfulPhone.ToString().LastIndexOf(',') == lawfulPhone.Length - 1)
- {
- lawfulPhone = lawfulPhone.Remove(lawfulPhone.Length - 1, 1);
- }
- }
- if (CorrectPhone.Trim().Length <= 0)
- {
- ErrorPhone = "没找到有效的手机号码!";
- }
- return ErrorPhone.Trim().Trim(',');
- }
- /// <summary>
- /// 获取字符串中的退订字符
- /// </summary>
- /// <param name="s"></param>
- /// <returns></returns>
- static string GetUnsubscribeCharacter(string s)
- {
- string retstr = "";
- if (s.ToUpper().Contains("回TD退订"))
- {
- retstr = "回TD退订";
- }
- else if (s.ToUpper().Contains("退订回TD"))
- {
- retstr = "退订回TD";
- }
- else if (s.ToUpper().Contains("退订回N"))
- {
- retstr = "退订回N";
- }
- else if (s.ToUpper().Contains("回N退订"))
- {
- retstr = "回N退订";
- }
- else if (s.ToUpper().Contains("退订N"))
- {
- retstr = "退订N";
- }
- else if (s.ToUpper().Contains("回复TD退订"))
- {
- retstr = "回复TD退订";
- }
- else if (s.ToUpper().Contains("退订复回TD"))
- {
- retstr = "退订回复TD";
- }
- else if (s.ToUpper().Contains("TD退订"))
- {
- retstr = "TD退订";
- }
- else if (s.ToUpper().Contains("退订TD"))
- {
- retstr = "退订TD";
- }
- return retstr;
- }
- /// <summary>
- /// 获取短信内容条数 并在最后一条为一个符号时去除符号
- /// </summary>
- /// <param name="s"></param>
- /// <param name="signature">签名字符 如:“【利亚方州】”</param>
- /// <returns></returns>
- public static int GetSendSmsCount(ref string s, string signature)
- {
- int count = 0;
- // string UnsubscribeCharacter = GetUnsubscribeCharacter(s);
- string tempStr = s;//.Replace(UnsubscribeCharacter.ToUpper(), "").Replace(UnsubscribeCharacter.ToLower(), "");
- bool isSignatureFront = false;//签名是否在前面
- if (signature != null)
- {
- if (tempStr.IndexOf(signature) == 0)
- {
- //签名在前面
- isSignatureFront = true;
- tempStr = tempStr.Substring(signature.Length);
- }
- else if (tempStr.IndexOf(signature) == (tempStr.Length - signature.Length))
- {
- //签名在后面
- tempStr = tempStr.Substring(0, tempStr.Length - signature.Length);
- isSignatureFront = false;
- }
- tempStr = tempStr.Replace(signature, "");
- }
- if (s.Length > 70)
- {
- count = s.Length / 67;
- int Remainder = (s.Length % 67);
- if (Remainder > 0)
- {
- count++;
- }
- if (Remainder == 1 || s.Length == 71)
- {
- string tempFilterChar = ",,.。??!!()(){}[]【】<>《》;::*%';|\\+-=*&^%$#@!~`";
- string LastChar = tempStr.Substring(tempStr.Length - 1);
- if (tempFilterChar.Contains(LastChar))
- {
- tempStr = tempStr.Substring(0, tempStr.Length - 1);
- }
- else
- {
- LastChar = tempStr.Substring(0, 1);
- if (tempFilterChar.Contains(LastChar))
- {
- tempStr = tempStr.Substring(1, tempStr.Length - 1);
- }
- else
- {
- int lastIndx1 = tempStr.LastIndexOf('!');
- int lastIndx2 = tempStr.LastIndexOf('!');
- int lastIndx3 = tempStr.LastIndexOf('.');
- int lastIndx4 = tempStr.LastIndexOf('。');
- if (lastIndx1 != -1)
- {
- tempStr = tempStr.Remove(lastIndx1, 1);
- }
- else if (lastIndx2 != -1)
- {
- tempStr = tempStr.Remove(lastIndx2, 1);
- }
- else if (lastIndx3 != -1)
- {
- tempStr = tempStr.Remove(lastIndx3, 1);
- }
- else if (lastIndx4 != -1)
- {
- tempStr = tempStr.Remove(lastIndx4, 1);
- }
- else
- {
- lastIndx1 = tempStr.LastIndexOf(',');
- lastIndx2 = tempStr.LastIndexOf(',');
- if (lastIndx1 != -1)
- {
- tempStr = tempStr.Remove(lastIndx1, 1);
- }
- else if (lastIndx2 != -1)
- {
- tempStr = tempStr.Remove(lastIndx2, 1);
- }
- }
- }
- }
- if (isSignatureFront)
- {
- s = signature + tempStr.Replace("\r\n", "");
- }
- else
- {
- s = tempStr.Replace("\r\n", "") + signature;
- }
- }
- }
- else if (s.Length > 0)
- {
- count = 1;
- }
- /* if (UnsubscribeCharacter.Trim().Length > 0)
- {
- s = s.Replace(UnsubscribeCharacter.ToUpper(), "").Replace(UnsubscribeCharacter.ToLower(), "");
- s = s + UnsubscribeCharacter.ToUpper();
- }*/
- return count;
- }
- /// <summary>
- /// 获取以","分隔的手机号 以指定手机号个数拆分成数组
- /// </summary>
- /// <param name="phoneString">以","分隔的手机号</param>
- /// <param name="count"></param>
- /// <returns></returns>
- public static string[] GetPhoneSplitCount(string phoneString, int count)
- {
- string[] tempPhones = phoneString.Trim().Split(',');
- List<string> tempPhoneList = new List<string>();
- tempPhoneList.AddRange(tempPhones);
- tempPhoneList.Sort();
- tempPhones = tempPhoneList.ToArray();
- tempPhoneList.Clear();
- int tempCount = 0;
- string tempPhoneStr = "";
- for (int i = 0; i < tempPhones.Length; i++)
- {
- tempCount++;
- if (tempCount == count)
- {
- tempPhoneStr += tempPhones[i];
- tempCount = 0;
- tempPhoneStr += "|";
- }
- else
- {
- if (tempPhoneStr == "")
- {
- tempPhoneStr += tempPhones[i];
- }
- else
- {
- tempPhoneStr += "," + tempPhones[i];
- }
- }
- }
- if (tempPhoneStr.Trim('|').Length > 0)
- {
- return tempPhoneStr.Trim('|').Split('|');
- }
- else
- {
- return new string[0];
- }
- }
- /// <summary>
- /// 域名转换为IP地址
- /// </summary>
- /// <param name="hostname">域名或IP地址 ""</param>
- /// <param name="isIP6">是否获取IP6地址</param>
- /// <returns>IP地址</returns>
- public static string HostnameToIP(string hostname, bool isIP6 = false)
- {
- string ipStr = hostname;
- try
- {
- System.Net.IPAddress[] IPs = System.Net.Dns.GetHostAddresses(hostname);
- foreach (System.Net.IPAddress ip in IPs)
- {
- string tempStr = ip.ToString();
- if (isIP6)
- {
- string[] temps = tempStr.Split(':');
- if (temps.Length == 8)
- {
- ipStr = tempStr;
- break;
- }
- }
- else
- {
- string[] temps = tempStr.Split('.');
- if (temps.Length == 4)
- {
- ipStr = tempStr;
- break;
- }
- }
- }
- }
- catch (Exception)
- {
- throw new Exception("转换IP地址错误");
- }
- return ipStr;
- }
- #endregion
- /// <summary>
- /// 过虑特殊字符
- /// </summary>
- /// <param name="characterString"></param>
- /// <returns></returns>
- public static string WorryingTooSpecialCharacter(string characterString)
- {
- return characterString
- .Replace(".", "")
- .Replace("*", "")
- .Replace("<", "")
- .Replace(">", "")
- .Replace("/", "")
- .Replace("\\", "")
- .Replace("\"", "")
- .Replace("|", "")
- .Replace(":", "")
- .Replace("?", "");
- }
- /// <summary>
- /// 获取完整路径 只能为文件夹目录路径 检查路径结尾是否存在 “\”符号 如果不存在添加上
- /// </summary>
- /// <param name="directoryPath"></param>
- /// <returns></returns>
- public static string GetFullDirectoryPath(string directoryPath)
- {
- if (directoryPath.LastIndexOf("\\") != directoryPath.Length - 1)
- {
- directoryPath = directoryPath + "\\";
- }
- return directoryPath;
- }
- /// <summary>
- /// 删除Thumbs.db 文件
- /// </summary>
- /// <param name="directoryPath"></param>
- public static void DeleteThumbs(string directoryPath)
- {
- LYFZ.WinAPI.CustomPublicMethod.ExecuteCmd("del " + GetFullDirectoryPath(directoryPath) + "Thumbs.db /f/s/q/a");
- }
- /// <summary>
- /// 删除空文件夹
- /// </summary>
- /// <param name="directoryPath">文件夹路径</param>
- public static void DeleteDirectory(string directoryPath)
- {
- DeleteThumbs(directoryPath);
- string[] directorys = System.IO.Directory.GetDirectories(directoryPath, "*", System.IO.SearchOption.AllDirectories);
- foreach (string dir in directorys)
- {
- try
- {
- DeleteThumbs(directoryPath);
- if (System.IO.Directory.GetFiles(dir).Length <= 0)
- {
- System.IO.Directory.Delete(dir);
- }
- }
- catch { }
- }
- try
- {
- if (System.IO.Directory.GetFiles(directoryPath).Length <= 0)
- {
- System.IO.Directory.Delete(directoryPath);
- }
- }
- catch { }
- }
- /// <summary>
- /// 执行CMD命令
- /// </summary>
- /// <param name="command">CMD命令字符串</param>
- /// <returns></returns>
- public static string ExecuteCmd(string command)
- {
- string str = command;
- System.Diagnostics.Process p = new System.Diagnostics.Process();
- p.StartInfo.FileName = "cmd.exe";
- p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
- p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
- p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
- p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
- p.StartInfo.CreateNoWindow = true;//不显示程序窗口
- p.Start();//启动程序
- //向cmd窗口发送输入信息
- p.StandardInput.WriteLine(str + " &exit");
- p.StandardInput.AutoFlush = true;
- //p.StandardInput.WriteLine("exit");
- //向标准输入写入要执行的命令。这里使用&是批处理命令的符号,表示前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死
- //同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令,后者表示必须前一个命令执行失败才会执行后面的命令
- //获取cmd窗口的输出信息
- string output = p.StandardOutput.ReadToEnd();
- p.WaitForExit();//等待程序执行完退出进程
- p.Close();
- return output;
- }
- /// <summary>
- /// 获取时间为"1900-01-01"的日期对象
- /// </summary>
- /// <returns></returns>
- public static DateTime GetNullDateTime()
- {
- return Convert.ToDateTime("1900-01-01");
- }
- /// <summary>
- /// 追加写入
- /// </summary>
- /// <param name="fullPath"></param>
- /// <param name="txt"></param>
- public static void AddWriter(string fullPath, string txt)
- {
- using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fullPath, true, Encoding.UTF8))
- {
- sw.WriteLine(txt);
- sw.Flush();
- sw.Close(); System.IO.File.WriteAllText(fullPath, "", Encoding.UTF8);
- }
- }
- /// <summary>
- /// 覆盖写入
- /// </summary>
- /// <param name="fullPath"></param>
- /// <param name="txt"></param>
- public static void CoverWriter(string fullPath, string txt)
- {
- System.IO.File.WriteAllText(fullPath, txt, Encoding.UTF8);
- }
- /// <summary>
- /// 获取机器硬件码
- /// </summary>
- /// <returns></returns>
- public static string GetHardwareCode()
- {
- string TempHardwareCode = "";
- TempHardwareCode = GetHDIDInfo() + "-" + GetNetCardMacAddress() + "-" + GetCpuInfo();
- if (TempHardwareCode == "NOHDID-NOMAC-NOCPUSN")
- {
- TempHardwareCode = "机器硬件码获取失败!";
- }
- return TempHardwareCode;
- }
- /// <summary>
- /// 获取机器硬件码
- /// </summary>
- /// <returns></returns>
- public static string GetHardwareCodeOne()
- {
- string TempHardwareCode = GetHDIDInfo() + "-" + GetCpuInfo();
- return TempHardwareCode.Replace("\"", "").Replace("&", "").Replace("#", "").Replace("$", "");
- }
- /// <summary>
- /// cpu序列号
- /// </summary>
- /// <returns></returns>
- public static string GetCpuInfo()
- {
- try
- {
- string cpuInfo = "";//cpu序列号
- System.Management.ManagementClass cimobject = new System.Management.ManagementClass("Win32_Processor");
- System.Management.ManagementObjectCollection moc = cimobject.GetInstances();
- foreach (System.Management.ManagementObject mo in moc)
- {
- /*List<string> tmepList = new List<string>();
- foreach (System.Management.PropertyData pdc in mo.Properties)
- {
- string valueStr = "";
- if (pdc.Value != null) {
- valueStr = pdc.Value.ToString();
- }
- tmepList.Add(pdc.Name + "|" + valueStr);
- }*/
- cpuInfo += mo.Properties["ProcessorId"].Value.ToString();
- }
- return ("CPUSN" + cpuInfo.ToString().Replace("-", ""));
- }
- catch
- {
- return "NOCPUSN";
- }
- }
- /// <summary>
- /// 获取硬盘ID
- /// </summary>
- /// <returns></returns>
- public static string GetHDIDInfo()
- {
- try
- {
- string HDid = "";
- System.Management.ManagementClass cimobject1 = new System.Management.ManagementClass("Win32_DiskDrive");
- System.Management.ManagementObjectCollection moc1 = cimobject1.GetInstances();
- foreach (System.Management.ManagementObject mo in moc1)
- {
- string modelValue = (string)mo.Properties["Model"].Value;
- if (!modelValue.Contains("USB Device"))
- {
- HDid += "SN:" + mo.Properties["SerialNumber"].Value.ToString().Trim() + modelValue;
- }
- }
- return ("HDID-" + HDid.ToString().Trim().Replace("-", "")).Trim().Replace(" ", "").ToUpper().Replace("DiskDevice".ToUpper(), "");
- }
- catch
- {
- return "NOHDID" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
- }
- }
- /// <summary>
- /// C盘序列号
- /// </summary>
- /// <returns></returns>
- public static string GetDiskVolumeSerialNumber()
- {
- System.Management.ManagementObject disk;
- disk = new System.Management.ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
- disk.Get();
- return disk.GetPropertyValue("VolumeSerialNumber").ToString();
- }
- /// <summary>
- /// 获取MAC地址
- /// </summary>
- /// <returns></returns>
- public static string GetNetCardMacAddress(string separator = "")
- {
- try
- {
- LYFZ.WinAPI.LocalNetworkCardObjects networkCarObjects = new WinAPI.LocalNetworkCardObjects();
- string retMacStr = "";
- if (networkCarObjects.PhysicalNICList.Count > 0)
- {
- retMacStr = "PhysicalNICList:";
- foreach (NetworkCardInfo cardinfo in networkCarObjects.PhysicalNICList)
- {
- retMacStr += cardinfo.MACPhysicalAddress.ToString() + "&";
- }
- }
- else if (networkCarObjects.WirelessLANList.Count > 0)
- {
- retMacStr = "WirelessLANList:";
- foreach (NetworkCardInfo cardinfo in networkCarObjects.WirelessLANList)
- {
- retMacStr += cardinfo.MACPhysicalAddress.ToString() + "&";
- }
- }
- else if (networkCarObjects.VirtualNetworkCardList.Count > 0)
- {
- retMacStr = "VirtualNetworkCardList:";
- foreach (NetworkCardInfo cardinfo in networkCarObjects.VirtualNetworkCardList)
- {
- retMacStr += cardinfo.MACPhysicalAddress.ToString() + "&";
- }
- }
- else
- {
- System.Management.ManagementClass mc;
- System.Management.ManagementObjectCollection moc;
- mc = new System.Management.ManagementClass("Win32_NetworkAdapterConfiguration");
- moc = mc.GetInstances();
- string str = "";
- foreach (System.Management.ManagementObject mo in moc)
- {
- if ((bool)mo["IPEnabled"] == true)
- {
- str = mo["MacAddress"].ToString();
- break;
- }
- }
- return "ManagementClass-" + str.ToUpper().Replace(":", separator).Replace("-", separator);
- }
- return retMacStr.Trim('&');
- }
- catch
- {
- return "NOMAC-" + GetHDIDInfo();
- }
- /* // 获取属性
- string caption = mo["Caption"].ToString(); //名称
- string[] addresses = (string[])mo["IPAddress"]; //IP地址
- string[] subnets = (string[])mo["IPSubnet"]; //子网掩码
- string[] gateways = (string[])mo["DefaultIPGateway"]; //网关
- string[] dnses = (string[])mo["DNSServerSearchOrder"]; //DNS
- ManagementBaseObject newIP;
- // 修改IP及子网掩码
- newIP = mo.GetMethodParameters("EnableStatic");
- newIP["IPAddress"] = new string[] { "192.168.2.51" };
- newIP["SubnetMask"] = new string[] { "255.255.255.0" }; //修改IP同时,需要填写子网掩码
- mo.InvokeMethod("EnableStatic", newIP, null);
- // 设置网关地址
- newIP = mo.GetMethodParameters("SetGateways");
- newIP["DefaultIPGateway"] = new string[] { "192.168.2.1" };
- mo.InvokeMethod("SetGateways", newIP, null);
- // 设置DNS
- newIP = mo.GetMethodParameters("SetDNSServerSearchOrder");
- newIP["DNSServerSearchOrder"] = new string[] { "192.168.1.10" };
- mo.InvokeMethod("SetDNSServerSearchOrder", newIP, null);*/
- }
- /// 显示本机各网卡的详细信息
- ///
- /// <summary>
- /// 指定秒数后关机
- /// </summary>
- /// <param name="time"></param>
- public static void ExitWindows(int time = 600)
- {
- ExecuteCmd("shutdown -s -t " + time.ToString());
- }
- /// <summary>
- /// 取消关机命令
- /// </summary>
- /// <param name="time"></param>
- public static void CancelExitWindows()
- {
- ExecuteCmd("shutdown -a");
- }
- /// <summary>
- /// 获取指定路径目录的容量信息
- /// </summary>
- /// <param name="dirPath">获取指定路径目录</param>
- /// <returns></returns>
- public static MyDriverInfo GetDiskFreeSpace(string dirPath)
- {
- MyDriverInfo dInfo = new MyDriverInfo();
- try
- {
- long freeBytes = 0;//可用大小
- long totalBytes = 0;//
- long totalFreeBytes = 0;
- dInfo.DriverPath = dirPath;
- if (Win32.GetDiskFreeSpace(dirPath, ref freeBytes, ref totalBytes, ref totalFreeBytes))
- {
- dInfo.FreeBytes = freeBytes;
- dInfo.TotalBytes = totalBytes;
- dInfo.TotalFreeBytes = totalFreeBytes;
- dInfo.ErrorMessages = "";
- }
- else
- {
- int errCode = System.Runtime.InteropServices.Marshal.GetLastWin32Error();//获取错误码。
- dInfo.ErrorMessages = Win32.GetSysErrMsg(errCode);
- }
- }
- catch (Exception ex)
- {
- dInfo.DriverPath = dirPath;
- dInfo.ErrorMessages = ex.Message;
- }
- return dInfo;
- }
- /// <summary>
- /// 获取系统物理总内存大小
- /// </summary>
- /// <returns>内存大小(单位M)</returns>
- public static int GetPhisicalMemory()
- {
- try
- {
- System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(); //用于查询一些如系统信息的管理对象
- searcher.Query = new System.Management.SelectQuery("Win32_PhysicalMemory ", "", new string[] { "Capacity" });//设置查询条件
- System.Management.ManagementObjectCollection collection = searcher.Get(); //获取内存容量
- System.Management.ManagementObjectCollection.ManagementObjectEnumerator em = collection.GetEnumerator();
- long capacity = 0;
- while (em.MoveNext())
- {
- System.Management.ManagementBaseObject baseObj = em.Current;
- if (baseObj.Properties["Capacity"].Value != null)
- {
- try
- {
- capacity += long.Parse(baseObj.Properties["Capacity"].Value.ToString());
- }
- catch
- {
- return 0;
- }
- }
- baseObj.Dispose();
- }
- searcher.Dispose();
- collection.Dispose();
- em.Dispose();
- return (int)(capacity / 1024 / 1024);
- }
- catch
- {
- return 0;
- }
- }
- /// <summary>
- /// 获取系统物理可用内存大小
- /// </summary>
- /// <returns>内存大小(单位M)</returns>
- public static int GetPhisicalUsableMemory()
- {
- try
- {
- double available = 0;
- //获取内存可用大小
- System.Management.ManagementClass cimobject2 = new System.Management.ManagementClass("Win32_PerfFormattedData_PerfOS_Memory");
- System.Management.ManagementObjectCollection moc2 = cimobject2.GetInstances();
- foreach (System.Management.ManagementObject mo2 in moc2)
- {
- available += Int64.Parse(mo2.Properties["AvailableMBytes"].Value.ToString());
- }
- moc2.Dispose();
- cimobject2.Dispose();
- return Convert.ToInt32(available);
- }
- catch
- {
- return 0;
- }
- }
- public static bool DataGridViewToExcel(string savePath, System.Windows.Forms.DataGridView m_DataView, BackgroundWorker backgroundWorker = null)
- {
- bool ret = false;
- string FileName = savePath;
- if (File.Exists(FileName))
- {
- File.Delete(FileName);
- }
- Biff8Excel.Excel.ExcelWorkbook wbook;
- Biff8Excel.Excel.ExcelWorksheet wsheet;
- //ExcelRow row;
- // Biff8Excel.Excel.ExcelCellLinkDictionary row;
- // Biff8Excel.Excel.ExcelCell cell;
- Biff8Excel.Excel.ExcelCellStyle style;
- //short x;
- // Create a Workbook Object and set a password to make it read-only
- //创建一个工作簿对象并设置密码,使其只读
- wbook = new Biff8Excel.Excel.ExcelWorkbook();
- wbook.SetDefaultFont("Arial", 10); // default to Arial,10
- //wbook.Password = "Excel";
- // Create 5 Worksheets
- //创建工作表
- wbook.CreateSheet("Sheet1");
- // you can get a reference to any sheet either by index (1 based) or sheet name
- // get a reference to the first sheet
- //你可以得到任何表的引用无论是索引(从1开始)或工作表名称
- //获取到第一片材的参考
- wsheet = wbook.GetSheet(1);
- // Or
- // wsheet = wbook.GetSheet("Sheet1");
- //likewise to set the active sheet when opened (defaults to the first sheet created)
- //打开(默认创建的第一个表)时,同样设置活动工作表
- wbook.SetActiveSheet = 1;
- // Or
- //wbook.SetActiveSheet = "Sheet1";
- //添加标题
- ushort rowIndex = 1;
- ushort cellIndex = 1;
- style = wbook.CreateStyle();
- style.Font.Bold = true;
- // style.Font.Colour = Biff8Excel.EnumColours.Blue;
- if (backgroundWorker != null)
- {
- backgroundWorker.ReportProgress(1, "正在创建标题...");
- }
- style.HorizontalAlignment = Biff8Excel.EnumHorizontalAlignment.Center;
- for (int i = 0; i < m_DataView.Columns.Count; i++)
- {
- if (m_DataView.Columns[i].Visible == true)
- {
- wsheet.AddCell(cellIndex, rowIndex, m_DataView.Columns[i].HeaderText.ToString(), style);
- cellIndex++;
- }
- }
- //导出内容
- //总计数器
- float sumCount = m_DataView.Rows.Count;
- rowIndex = 2;
- cellIndex = 1;
- for (int i = 0; i < m_DataView.Rows.Count; i++)
- {
- if (backgroundWorker != null)
- {
- try
- {
- int currentProgres = Convert.ToInt32(1000 / sumCount * rowIndex);
- backgroundWorker.ReportProgress(currentProgres, "正在导出第" + rowIndex.ToString() + "条数据...");
- }
- catch { }
- }
- cellIndex = 1;
- Biff8Excel.Excel.ExcelCellStyle styleValue = wbook.CreateStyle();
- for (int j = 0; j < m_DataView.Columns.Count; j++)
- {
- if (m_DataView.Columns[j].Visible == true)
- {
- object cellValue = "";
- System.Windows.Forms.DataGridViewCell dgCell = m_DataView.Rows[i].Cells[j];
- if (dgCell.Value != null)
- {
- cellValue = dgCell.Value;
- }
- if (m_DataView.Rows[i].Tag != null && m_DataView.Rows[i].Tag.ToString() == "FontStyle.Bold")
- {
- styleValue.Font.Bold = true;
- }
- else
- {
- if (dgCell != null && dgCell.Style != null && dgCell.Style.Font != null)
- {
- styleValue.Font.Bold = dgCell.Style.Font.Bold;
- }
- }
- if (dgCell != null && dgCell.Style != null && dgCell.Style.Font != null)
- {
- styleValue.Font.Size = Convert.ToUInt16(dgCell.Style.Font.Size);
- }
- //styleValue.Pattern = EnumFill.Solid;
- // styleValue.PatternForeColour = EnumColours.Blue;
- // styleValue.BorderColour = EnumColours.Grey80;
- // styleValue.BorderLineStyle = EnumLineStyle.Thin;
- // styleValue.Font.Colour = Biff8Excel.EnumColours.BrightGreen;
- wsheet.AddCell(cellIndex, rowIndex, cellValue, styleValue);
- cellIndex++;
- }
- }
- rowIndex++;
- }
- wbook.Save(FileName);
- ret = true;
- return ret;
- }
- public static bool DataGridViewToExcel(string savePath, System.Data.DataTable m_table, List<string> ColumnNames = null, BackgroundWorker backgroundWorker = null)
- {
- bool ret = false;
- string FileName = savePath;
- if (File.Exists(FileName))
- {
- File.Delete(FileName);
- }
- Biff8Excel.Excel.ExcelWorkbook wbook;
- Biff8Excel.Excel.ExcelWorksheet wsheet;
- //ExcelRow row;
- // Biff8Excel.Excel.ExcelCellLinkDictionary row;
- // Biff8Excel.Excel.ExcelCell cell;
- Biff8Excel.Excel.ExcelCellStyle style;
- //short x;
- // Create a Workbook Object and set a password to make it read-only
- //创建一个工作簿对象并设置密码,使其只读
- wbook = new Biff8Excel.Excel.ExcelWorkbook();
- wbook.SetDefaultFont("Arial", 10); // default to Arial,10
- //wbook.Password = "Excel";
- // Create 5 Worksheets
- //创建工作表
- wbook.CreateSheet("Sheet1");
- // you can get a reference to any sheet either by index (1 based) or sheet name
- // get a reference to the first sheet
- //你可以得到任何表的引用无论是索引(从1开始)或工作表名称
- //获取到第一片材的参考
- wsheet = wbook.GetSheet(1);
- // Or
- // wsheet = wbook.GetSheet("Sheet1");
- //likewise to set the active sheet when opened (defaults to the first sheet created)
- //打开(默认创建的第一个表)时,同样设置活动工作表
- wbook.SetActiveSheet = 1;
- // Or
- //wbook.SetActiveSheet = "Sheet1";
- //添加标题
- ushort rowIndex = 1;
- ushort cellIndex = 1;
- style = wbook.CreateStyle();
- style.Font.Bold = true;
- //style.Font.Colour = Biff8Excel.EnumColours.Blue;
- if (backgroundWorker != null)
- {
- backgroundWorker.ReportProgress(1, "正在创建标题...");
- }
- style.HorizontalAlignment = Biff8Excel.EnumHorizontalAlignment.Center;
- if (ColumnNames != null && ColumnNames.Count > 0)
- {
- for (int i = 0; i < ColumnNames.Count; i++)
- {
- wsheet.AddCell(cellIndex, rowIndex, ColumnNames[i], style);
- cellIndex++;
- }
- }
- else
- {
- for (int i = 0; i < m_table.Columns.Count; i++)
- {
- wsheet.AddCell(cellIndex, rowIndex, m_table.Columns[i].ColumnName, style);
- cellIndex++;
- }
- }
- //导出内容
- //总计数器
- float sumCount = m_table.Rows.Count;
- rowIndex = 2;
- cellIndex = 1;
- for (int i = 0; i < m_table.Rows.Count; i++)
- {
- if (backgroundWorker != null)
- {
- try
- {
- int currentProgres = Convert.ToInt32(1000 / sumCount * rowIndex);
- backgroundWorker.ReportProgress(currentProgres, "正在导出第" + rowIndex.ToString() + "条数据...");
- }
- catch { }
- }
- cellIndex = 1;
- for (int j = 0; j < m_table.Columns.Count; j++)
- {
- object cellValue = "";
- if (m_table.Rows[i][j] != null)
- {
- cellValue = m_table.Rows[i][j];
- }
- wsheet.AddCell(cellIndex, rowIndex, cellValue);
- cellIndex++;
- }
- rowIndex++;
- }
- wbook.Save(FileName);
- ret = true;
- return ret;
- }
- /// <summary>
- /// Excel数据导入Datable
- /// </summary>
- /// <param name="fileName"></param>
- /// <returns></returns>
- public static System.Data.DataTable GetExcelDatatable(string fileName, string table = "Sheet1")
- {
- string fileExtenSion;
- fileExtenSion = System.IO.Path.GetExtension(fileName);
- string connstr2003 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
- string connstr2007 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=YES\"";
- System.Data.OleDb.OleDbConnection conn;
- if (fileExtenSion.ToLower() == ".xls")
- {
- try
- {
- conn = new System.Data.OleDb.OleDbConnection(connstr2003);
- conn.Open();
- }
- catch
- {
- conn = new System.Data.OleDb.OleDbConnection(connstr2007);
- conn.Open();
- }
- }
- else
- {
- conn = new System.Data.OleDb.OleDbConnection(connstr2007);
- conn.Open();
- }
- System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
- //获取Excel的第一个Sheet名称
- string sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim();
- string sql = "select * from [" + sheetName + "]";
- System.Data.OleDb.OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter(sql, conn);
- System.Data.DataSet ds = new System.Data.DataSet();
- conn.Close();
- try
- {
- da.Fill(ds, table);
- System.Data.DataTable dt = ds.Tables[0];
- RemoveEmpty(dt);
- return dt;
- }
- catch (Exception err)
- {
- System.Windows.Forms.MessageBox.Show("操作失败!" + err.ToString());
- return null;
- }
- }
- /// <summary>
- /// 移除空行
- /// </summary>
- /// <param name="dt"></param>
- public static void RemoveEmpty(System.Data.DataTable dt)
- {
- List<System.Data.DataRow> removelist = new List<System.Data.DataRow>();
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- bool rowdataisnull = true;
- for (int j = 0; j < dt.Columns.Count; j++)
- {
- if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
- {
- rowdataisnull = false;
- }
- }
- if (rowdataisnull)
- {
- removelist.Add(dt.Rows[i]);
- }
- }
- for (int i = 0; i < removelist.Count; i++)
- {
- dt.Rows.Remove(removelist[i]);
- }
- }
- /// <summary>
- /// 获取MyThemeColor
- /// </summary>
- /// <returns></returns>
- public static string GetSubFunctionMyThemeColor()
- {
- string retValue = "";
- string colorPath1 = LYFZ.WinAPI.CustomPublicMethod.GetFullDirectoryPath(LYFZ.WinAPI.CustomPublicMethod.BasePath) + LYFZ.WinAPI.SDKSecurity.Decode("fkyEXay6AVDmUi548qZKh7B573nFjFv6").Trim();
- string colorPath2 = LYFZ.WinAPI.CustomPublicMethod.GetFullDirectoryPath(LYFZ.WinAPI.CustomPublicMethod.BasePath) + LYFZ.WinAPI.SDKSecurity.Decode("fkyEXay6AVDaVY1mQhJGaQ==").Trim();
- if (System.IO.File.Exists(colorPath1))
- {
- retValue += LYFZ.WinAPI.SDKSecurity.GetMD5HashFromFile(colorPath1);
- }
- if (System.IO.File.Exists(colorPath2))
- {
- retValue += LYFZ.WinAPI.SDKSecurity.GetMD5HashFromFile(colorPath2);
- }
- return retValue;
- }
- /// <summary>
- /// 获取MyThemeColor
- /// </summary>
- /// <returns></returns>
- public static string GetSubFunctionMyThemeColorSrc()
- {
- return "f56a4f1074825056202037b9723909f1cb7d1b1101a6ecbe4d7482294cd46a30";
- }
- /// <summary>
- /// 检查日期格式
- /// </summary>
- /// <param name="str">日期</param>
- /// <returns></returns>
- public static bool IsTime(string str)
- {
- 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-))$");
- }
- #region 获取公网IP
- /// <summary>
- /// 获取公网IP
- /// </summary>
- /// <returns></returns>
- public static string GetNetIP(string url = "")
- {
- string tempIP = "0.0.0.0";
- try
- {
- string netIPUrl = GetNetIPUrl(url);
- System.Net.WebRequest wr = System.Net.WebRequest.Create(netIPUrl);
- System.IO.Stream s = wr.GetResponse().GetResponseStream();
- System.IO.StreamReader sr = new System.IO.StreamReader(s, System.Text.Encoding.GetEncoding("gb2312"));
- string all = sr.ReadToEnd(); //读取网站的数据
- int start = all.IndexOf("[") + 1;
- int end = all.IndexOf("]", start);
- tempIP = all.Substring(start, end - start);
- sr.Close();
- s.Close();
- }
- catch
- {
- tempIP = "0.0.0.0";
- }
- return tempIP;
- }
- /// <summary>
- /// 获取公网IP查询接口地址
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- public static string GetNetIPUrl(string url = "")
- {
- string netIPUrl = "http://1111.ip138.com/ic.asp";
- try
- {
- if (url.Trim().Length > 0)
- {
- System.Net.WebRequest wr = System.Net.WebRequest.Create(url);
- System.IO.Stream s = wr.GetResponse().GetResponseStream();
- System.IO.StreamReader sr = new System.IO.StreamReader(s, System.Text.Encoding.GetEncoding("gb2312"));
- netIPUrl = sr.ReadToEnd(); //读取网站的数据
- sr.Close();
- s.Close();
- }
- }
- catch
- {
- netIPUrl = "http://1111.ip138.com/ic.asp";
- }
- return netIPUrl;
- }
- #endregion
- /// <summary>
- /// 返回正确的签名
- /// </summary>
- /// <param name="timestamp"></param>
- /// <param name="nonce"></param>
- /// <param name="token"></param>
- /// <returns></returns>
- public static string GetSignature(string timestamp, string nonce, string token = null)
- {
- var arr = new[] { token, timestamp, nonce }.OrderBy(z => z).ToArray();
- var arrString = string.Join("", arr);
- //var enText = FormsAuthentication.HashPasswordForStoringInConfigFile(arrString, "SHA1");//使用System.Web.Security程序集
- var sha1 = System.Security.Cryptography.SHA1.Create();
- var sha1Arr = sha1.ComputeHash(Encoding.UTF8.GetBytes(arrString));
- StringBuilder enText = new StringBuilder();
- foreach (var b in sha1Arr)
- {
- enText.AppendFormat("{0:x2}", b);
- }
- return enText.ToString();
- }
- #region 实体和json互转方法 2017-04-10 杨云奕 添加
-
- /// <summary>
- /// 实体转json
- /// </summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static string ObjectToJson(object obj)
- {
- DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
- MemoryStream stream = new MemoryStream();
- serializer.WriteObject(stream, obj);
- byte[] dataBytes = new byte[stream.Length];
- stream.Position = 0;
- stream.Read(dataBytes, 0, (int)stream.Length);
- return Encoding.UTF8.GetString(dataBytes);
- }
- // 从一个Json串生成对象信息
- public static object JsonToObject(string jsonString, object obj)
- {
- DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
- MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
- return serializer.ReadObject(mStream);
- }
- public static object JsonToObject<T>(string jsonString, T obj)
- {
- jsonString = jsonString.Replace(":\"False\"", ":\"false\"").Replace(":\"True\"", ":\"true\"");
- DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
- MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
- return serializer.ReadObject(mStream);
- }
- #endregion
- }
- //创建一个委托,是为访问控件服务的。
- public delegate void DUpdateControl();
- /// <summary>
- /// 上传文件
- /// </summary>
- public class UploadFile
- {
- public UploadFile()
- {
- ContentType = "application/octet-stream";
- }
- public string Name { get; set; }
- public string Filename { get; set; }
- public string ContentType { get; set; }
- public byte[] Data { get; set; }
- }
- }
|