代码记录
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了代码记录相关的知识,希望对你有一定的参考价值。
前言
趁时间没事可做,今天下午索性做些无聊的事情。
1.根据规则将搜索表单内提交的有效数据封装成搜索字符串返回
form表单提交时,后台可以直接接受表单提交的数据,但有时我们如果要根据自己的需求去接受对应的控件内容,这时我们就要重新编译net内部的数据。以下代码是对筛选条件的处理。
/// <summary> /// 根据规则将搜索表单内提交的有效数据封装成搜索字符串返回 /// </summary> /// <param name="httpRequest">Request对象</param> /// <returns>搜索字符串</returns> public string GetQueryCondition() { string wheres = " 1=1 "; string[] whereKeys =Request.Form.AllKeys; foreach (string curWhere in whereKeys.Where(curWhere => Request.Form[curWhere] != null)) { Debug.Assert(curWhere != null, "curWhere != null"); if (curWhere.Trim().Equals(("X-Requested-With").Trim()) || Request.Form[curWhere] == string.Empty || Request.Form[curWhere] == null) continue; if (CheckForm(Request.Form[curWhere])) { wheres = wheres + " and 1=2"; continue; } if (curWhere.IndexOf("_TInt", System.StringComparison.Ordinal) > 0) wheres = wheres + " and " + curWhere.Substring(0, curWhere.Length - 5) + "=" + Request.Form[curWhere]; else if (curWhere.IndexOf("_TDateBegin", System.StringComparison.Ordinal) > 0) { } else if (curWhere.IndexOf("_TString", System.StringComparison.Ordinal) > 0) wheres = wheres + " and " + curWhere.Substring(0, curWhere.Length - 8) + "=‘" + Request.Form[curWhere]+"‘"; else wheres = wheres + " and charindex(‘" + Request.Form[curWhere] + "‘," + curWhere + ")>0"; } return wheres; } /// <summary> /// 查看提交表单(参数)是否包含非法字符 2014-01-14 JiYanan /// </summary> /// <param name="txt">表单(参数)值</param> /// <returns>true包含非法字符 false不包含非法字符</returns> public bool CheckForm(string txt) { //去掉了- string keyWords = "exec1xp_1sp_1declare1cmd1and1insert1select1de[email protected]1;1(1)1[1]1{1}1%1*1‘1!1<1>1=1^1--1+1/10x1|"; string[] keyWordsArr = keyWords.Split(‘1‘); txt = txt.ToLower(); foreach (string words in keyWordsArr) { if (txt.IndexOf(words) > -1) { return true; } } return false; }
2.返回类(接口转为json传递的时候使用)
异步调用后台方法,挥着编写接口的时候,我们一般都会希望我们的返回值是一个json,我一般会把这个json定义如下err,msg,data.其中err为错误编码,msg为错误信息,data就是对应的数据集。其中data我们可以根据自己的需求去定义data类型。一直器用起来方便。
using Dictionary; using Dispose; using Newtonsoft.Json; using System; using System.Collections.Generic; namespace StrokeInterface { /// <summary> /// 接口通用返回父类 /// </summary> internal class InterfaceResultBase { /// <summary> /// 错误号 /// </summary> public int Err { get; set; } /// <summary> /// 错误信息 /// </summary> public string Msg { get; set; } public InterfaceResultBase(int err, string msg) { Err = err; Msg = msg; } public virtual string ToJson(AESHelper aes) { return "{\\"err\\":" + Err.ToString() + ",\\"msg\\":\\"" + Msg + "\\"}"; } /// <summary> /// 为子类提供通用加密方法 /// </summary> /// <param name="data">已AES加密的Data</param> /// <returns></returns> protected string ToJsonByAes_Base(AESHelper aes, object obj) { string str = JsonConvert.SerializeObject(obj); return "{\\"err\\":" + Err.ToString() + ",\\"msg\\":\\"" + Msg + "\\",Data:[\\"" + aes.AESEncrypt(str) + "\\"]}"; } } /// <summary> /// 接口通用 IList<object> /// </summary> internal class InterfaceResultIList : InterfaceResultBase { /// <summary> /// 数据信息 /// </summary> public IList<object> Data { get; set; } public InterfaceResultIList(int err, string msg, IList<object> data) : base(err, msg) { Data = data; } /// <summary> /// 调用父类方法处理Data加密 /// </summary> /// <param name="aes"></param> /// <returns></returns> public override string ToJson(AESHelper aes) { return ToJsonByAes_Base(aes, Data); } } /// <summary> /// 接口通用 IDictionary /// </summary> internal class InterfaceResultIDictionary : InterfaceResultBase { /// <summary> /// 数据信息 /// </summary> public IDictionary<string, object> Data { get; set; } public InterfaceResultIDictionary(int err, string msg, IDictionary<string, object> data) : base(err, msg) { Data = data; } /// <summary> /// 调用父类方法处理Data加密 /// </summary> /// <param name="aes"></param> /// <returns></returns> public override string ToJson(AESHelper aes) { return ToJsonByAes_Base(aes, Data); } } /// <summary> /// 接口通用 IList<KeyValuePair<string ,object>> /// </summary> internal class InterfaceResultIListKV : InterfaceResultBase { /// <summary> /// 数据信息 /// </summary> public IList<KeyValuePair<string, object>> Data { get; set; } public InterfaceResultIListKV(int err, string msg, IList<KeyValuePair<string, object>> data) : base(err, msg) { Data = data; } /// <summary> /// 调用父类方法处理Data加密 /// </summary> /// <param name="aes"></param> /// <returns></returns> public override string ToJson(AESHelper aes) { return ToJsonByAes_Base(aes, Data); } } /// <summary> /// 接口通用 Object /// </summary> internal class InterfaceResultObject : InterfaceResultBase { /// <summary> /// 数据信息 /// </summary> public Object Data { get; set; } public InterfaceResultObject(int err, string msg, Object data) : base(err, msg) { Data = data; } /// <summary> /// 调用父类方法处理Data加密 /// </summary> /// <param name="aes"></param> /// <returns></returns> public override string ToJson(AESHelper aes) { return ToJsonByAes_Base(aes, Data); } } /// <summary> /// 接口通用 KeyValuePair /// </summary> internal class InterfaceResultKV : InterfaceResultBase { /// <summary> /// 数据信息 /// </summary> public Dictionary<string, object> Data { get; set; } public InterfaceResultKV(int err, string msg, Dictionary<string, object> data) : base(err, msg) { Data = data; } /// <summary> /// 调用父类方法处理Data加密 /// </summary> /// <param name="aes"></param> /// <returns></returns> public override string ToJson(AESHelper aes) { return ToJsonByAes_Base(aes, Data); } } /// <summary> /// 通用接口返回类 /// </summary> internal class InterfaceResult { public InterfaceResultBase IRes { get; set; } /// <summary> /// 只需要返回正确/错误 /// </summary> /// <param name="iCode"></param> /// <param name="err"></param> public InterfaceResult(string iCode, int err) { DictBLL dbl = new DictBLL("StrokeManage/interface/" + iCode + "Err"); IRes = new InterfaceResultBase(err, dbl.GetText(err.ToString())); } /// <summary> /// 适合于返回实体集合,实体名作为参数名 IList<object> /// </summary> /// <param name="iCode"></param> /// <param name="err"></param> /// <param name="data"></param> public InterfaceResult(string iCode, int err, IList<object> data) { DictBLL dbl = new DictBLL("StrokeManage/interface/" + iCode + "Err"); IRes = new InterfaceResultIList(err, dbl.GetText(err.ToString()), data); } /// <summary> /// 适用于返回键值对集合 自定义参数名 IDictionary<string, object> /// </summary> /// <param name="iCode"></param> /// <param name="err"></param> /// <param name="data"></param> public InterfaceResult(string iCode, int err, IDictionary<string, object> data) { DictBLL dbl = new DictBLL("StrokeManage/interface/" + iCode + "Err"); IRes = new InterfaceResultIDictionary(err, dbl.GetText(err.ToString()), data); } /// <summary> /// 适用于返回键值对集合 自定义参数名 IList<KeyValuePair<string ,object>> /// </summary> /// <param name="iCode"></param> /// <param name="err"></param> /// <param name="data"></param> public InterfaceResult(string iCode, int err, IList<KeyValuePair<string, object>> data) { DictBLL dbl = new DictBLL("StrokeManage/interface/" + iCode + "Err"); IRes = new InterfaceResultIListKV(err, dbl.GetText(err.ToString()), data); } /// <summary> /// 适合于返回单个实体 实体名作为参数名 Object /// </summary> /// <param name="iCode"></param> /// <param name="err"></param> /// <param name="data"></param> public InterfaceResult(string iCode, int err, Object data) { DictBLL dbl = new DictBLL("StrokeManage/interface/" + iCode + "Err"); IRes = new InterfaceResultObject(err, dbl.GetText(err.ToString()), data); } /// <summary> /// 适合于返回单个键值对 自定义参数名 KeyValuePair<string ,object> /// </summary> /// <param name="iCode"></param> /// <param name="err"></param> /// <param name="data"></param> public InterfaceResult(string iCode, int err, Dictionary<string, object> data) { DictBLL dbl = new DictBLL("StrokeManage/interface/" + iCode + "Err"); IRes = new InterfaceResultKV(err, dbl.GetText(err.ToString()), data); } /// <summary> /// 适合于只需要返回一个参数 自定义参数名 /// </summary> /// <param name="iCode"></param> /// <param name="err"></param> /// <param name="key">键</param> /// <param name="value">值</param> public InterfaceResult(string iCode, int err, string key, object value) { DictBLL dbl = new DictBLL("StrokeManage/interface/" + iCode + "Err"); Dictionary<string, object> data_kv = new Dictionary<string, object>(); data_kv.Add(key, value); IRes = new InterfaceResultKV(err, dbl.GetText(err.ToString()), data_kv); } /// <summary> /// 将结果转换为json /// </summary> /// <returns>json字符串</returns> public string ToJson() { return JsonConvert.SerializeObject(IRes); } /// <summary> /// 将结果转换为json /// </summary> /// <returns>json字符串</returns> public string ToJson(AESHelper aes) { return IRes.ToJson(aes); } } }
3.加密
3.1ase加密是个好东西,其中“+”要特别处理。
public class AESHelper { private byte[] aesKey = Encoding.Default.GetBytes("Dr6sg!UdnLEyu*34"); private byte[] aesIv = Encoding.Default.GetBytes("aEg$H*kwov93vQVn"); public AESHelper() { } public AESHelper(string aesKey_,string aesIv_) { aesKey = Encoding.Default.GetBytes(aesKey_); aesIv = Encoding.Default.GetBytes(aesIv_); } /// <summary> /// 设置加密 秘钥 /// </summary> /// <param name="aesKey_"></param> /// <param name="aesIv_"></param> public void SetKeyIv(string aesKey_,string aesIv_) { aesKey = Encoding.Default.GetBytes(aesKey_); aesIv = Encoding.Default.GetBytes(aesIv_); } /// <summary> /// AES加密算法(默认秘钥) /// </summary> /// <param name="plainText">明文字符串</param> /// <returns>将加密后的密文转换为Base64编码,以便显示</returns> public string AESEncrypt(string plainText) { //分组加密算法 SymmetricAlgorithm des = Rijndael.Create(); byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字节数组 //设置密钥及密钥向量 des.Key = aesKey; des.IV = aesIv; byte[] cipherBytes = null; using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cipherBytes = ms.ToArray();//得到加密后的字节数组 cs.Close(); ms.Close(); } } return Convert.ToBase64String(cipherBytes); } /// <summary> /// AES解密(默认秘钥) /// </summary> /// <param name="cipherText">密文字符串</param> /// <returns>返回解密后的明文字符串</returns> public string AESDecrypt(string showText) { byte[] cipherText = Convert.FromBase64String(showText); SymmetricAlgorithm des = Rijndael.Create(); des.Key = aesKey; des.IV = aesIv; byte[] decryptBytes = new byte[cipherText.Length]; using (MemoryStream ms = new MemoryStream(cipherText)) { using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read)) { try { cs.Read(decryptBytes, 0, decryptBytes.Length); cs.Close(); ms.Close(); } catch (Exception ex) { } } } return Encoding.UTF8.GetString(decryptBytes).Replace("\\0", ""); ///将字符串后尾的‘\\0‘去掉 } /// <summary> /// AES加密算法(传入秘钥) /// </summary> /// <param name="plainText">明文字符串</param> /// <param name="key">key</param> /// <param name="iv">iv</param> /// <returns>将加密后的密文转换为Base64编码,以便显示</returns> public string AESEncrypt(string plainText,string key,string iv) { //分组加密算法 SymmetricAlgorithm des = Rijndael.Create(); byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字节数组 //设置密钥及密钥向量 des.Key = Encoding.Default.GetBytes(key); des.IV = Encoding.Default.GetBytes(iv); byte[] cipherBytes = null; using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cipherBytes = ms.ToArray();//得到加密后的字节数组 cs.Close(); ms.Close(); } } return Convert.ToBase64String(cipherBytes); } /// <summary> /// AES解密(传入秘钥) /// </summary> /// <param name="cipherText">密文字符串</param> /// <param name="key">key</param> /// <param name="iv">iv</param> /// <returns>返回解密后的明文字符串</returns> public string AESDecrypt(string showText, string key, string iv) { byte[] cipherText = Convert.FromBase64String(showText); SymmetricAlgorithm des = Rijndael.Create(); des.Key = Encoding.Default.GetBytes(key); des.IV = Encoding.Default.GetBytes(iv); byte[] decryptBytes = new byte[cipherText.Length]; using (MemoryStream ms = new MemoryStream(cipherText)) { using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read)) { cs.Read(decryptBytes, 0, decryptBytes.Length); cs.Close(); ms.Close(); } } return Encoding.UTF8.GetString(decryptBytes).Replace("\\0", ""); ///将字符串后尾的‘\\0‘去掉 } /// <summary> /// AES加密算法(默认秘钥)(处理 "" "+" 问题) /// </summary> /// <param name="plainText">明文字符串</param> /// <returns>将加密后的密文转换为Base64编码,以便显示</returns> public string AESEncrypt_(string plainText) { return AESEncrypt(plainText).Replace(" ", "+"); } /// <summary> /// AES解密(默认秘钥)(处理 "" "+" 问题) /// </summary> /// <param name="cipherText">密文字符串</param> /// <returns>返回解密后的明文字符串</returns> public string AESDecrypt_(string showText) { return AESDecrypt(showText).Replace("+", "%2B"); ///将字符串后尾的‘\\0‘去掉 } /// <summary> /// AES加密算法(传入秘钥)(处理 "" "+" 问题) /// </summary> /// <param name="plainText">明文字符串</param> /// <param name="key">key</param> /// <param name="iv">iv</param> /// <returns>将加密后的密文转换为Base64编码,以便显示</returns> public string AESEncrypt_(string plainText, string key, string iv) { return AESEncrypt(plainText, key, iv).Replace(" ", "+"); } /// <summary> /// AES解密(传入秘钥)(处理 "" "+" 问题) /// </summary> /// <param name="cipherText">密文字符串</param> /// <param name="key">key</param> /// <param name="iv">iv</param> /// <returns>返回解密后的明文字符串</returns> public string AESDecrypt_(string showText, string key, string iv) { return AESDecrypt(showText, key, iv).Replace("+", "%2B"); ///将字符串后尾的‘\\0‘去掉 } }
3.2.md5加密
/// <summary> /// md5加密(已替换,不是基本MD5) /// </summary> /// <param name="str">字符串</param> /// <returns>32位加密结果</returns> public string EncryptMd5(string str) { str = str.ToLower(); str = str.Replace("a", "Th"); str = str.Replace("d", "ye"); str = str.Replace("e", "8Ye"); str = str.Replace("f", "qrS"); str = str.Replace("h", "R8"); str = str.Replace("p", "at"); str = str.Replace("x", "."); str = str.Replace("1", "UTS9"); str = str.Replace("8", "a"); return Md5(str); } /// <summary> /// 标准md5加密 /// </summary> /// <param name="str">字符串</param> /// <returns>32位加密结果</returns> public string Md5(string str) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); //得到加密字节数组 byte[] encryptedBytes = md5.ComputeHash(Encoding.ASCII.GetBytes(str)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < encryptedBytes.Length; i++) { //转换成十六进制数据 sb.AppendFormat("{0:x2}", encryptedBytes[i]); } return sb.ToString(); }
3.3des加密
#region 加密 解密 private static Byte[] KEY_64 { get { return new byte[] { 12, 213, 58, 56, 8, 4, 99, 61 }; } } private static Byte[] IV_64 { get { return new byte[] { 2, 46, 226, 28, 36, 4, 163, 10 }; } } /// <summary> /// 加密 /// </summary> /// <param name="name"></param> /// <returns></returns> public static string EncryptCookie(string str)//标准的DES加密 关键字、数据加密 { if (string.IsNullOrEmpty(str)) { return null; } else { DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider(); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateEncryptor(KEY_64, IV_64), CryptoStreamMode.Write); StreamWriter sw = new StreamWriter(cs); sw.Write(str); sw.Flush(); cs.FlushFinalBlock(); ms.Flush(); //再转换为一个字符串 return Convert.ToBase64String(ms.GetBuffer(), 0, Int32.Parse(ms.Length.ToString())) + ","; } } /// <summary> /// 解密(原始) /// </summary> /// <param name="temp"></param> /// <returns></returns> public static string DecryptCookie_(string str)//标准的DES解密 { if (string.IsNullOrEmpty(str)) { return null; } else { DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider(); //从字符串转换为字节组 Byte[] buffer = Convert.FromBase64String(str); MemoryStream ms = new MemoryStream(buffer); CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateDecryptor(KEY_64, IV_64), CryptoStreamMode.Read); StreamReader sr = new StreamReader(cs); return sr.ReadToEnd(); } } /// <summary> /// 解密 用于URL参数解密 /// </summary> /// <param name="temp"></param> /// <returns></returns> public static string DecryptCookie(string str)//标准的DES解密 { if (string.IsNullOrEmpty(str)) { return null; } else { str = str.Replace(" ", "+").TrimEnd(‘,‘); DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider(); //从字符串转换为字节组 Byte[] buffer = Convert.FromBase64String(str); MemoryStream ms = new MemoryStream(buffer); CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateDecryptor(KEY_64, IV_64), CryptoStreamMode.Read); StreamReader sr = new StreamReader(cs); return sr.ReadToEnd(); } } #endregion
4.mvc 分页操作
4.1.后台数据处理
4.1.1.分页应该算是所有系统中均会有的一个功能,一下是一个项目中用到的分页方法。
/// <summary> /// 获取grid部分的内容wheres条件 /// </summary> /// <typeparam name="T">泛型类型(实体类类型)</typeparam> /// <param name="getListCount">获取数据数量的方法委托</param> /// <param name="getList">获取当前页的数据方法委托 </param> /// <param name="prows">每页数据量</param> /// <param name="wheres">where 条件</param> /// <param name="orders">排序字段</param> /// <param name="controllerName">要获取数据的局部视图名(与当前的视图名相同即可)</param> /// <returns></returns> public ActionResult PartialListData<T>(GetListCount getListCount, GetList<T> getList, int prows,string wheres, string orders, string controllerName) { int count = getListCount(wheres); int pageIndex = 1; if (Request.QueryString["pageIndex"] != null) int.TryParse(Request.QueryString["pageIndex"], out pageIndex); IList<T> list = getList(prows, pageIndex, wheres, orders); ViewBag.pageCurren = pageIndex; ViewBag.pageCount = count / 10 == 0 ? count % 10 == 0 ? 0 : 1 : count % 10 == 0 ? count / 10 : count / 10 + 1; ViewBag.dataCount = count; return PartialView(controllerName, list); }
4.1.2定义以上参数GetListCount 参数以获得分页数据数量
/// <summary> /// 获取数据数量的方法委托 /// </summary> /// <param name="wheres">where条件</param> /// <returns></returns> public delegate int GetListCount(string wheres);
4.1.3.定义参数委托获取线束数据集
/// <summary> /// 获取当前页的数据方法委托 /// </summary> /// <typeparam name="T">泛型类型(实体类类型)</typeparam> /// <param name="prows">每页数据量</param> /// <param name="pages">页码</param> /// <param name="wheres">where条件</param> /// <param name="orders">排序字段</param> /// <returns>数据泛型集合</returns> public delegate IList<T> GetList<T>(int prows, int pages, string wheres, string orders);
4.2 前台页面处理
4.2.1.前台脚本
<script language="javascript" type="text/javascript"> var pageCount = @{@html.Raw(@ViewBag.pageCount+";");} function ChangeUrl() { var indexValue = $("#pageIndex").attr("value"); if (isNaN(indexValue)) { $("#pageIndex").attr("value", ""); } else { if (indexValue > pageCount) { parent.extAlert("页码超出索引"); $("#pageIndex").attr("value", ""); } else if (indexValue < 1) { parent.extAlert("页码无效,请输入大于0的合法页码数"); $("#pageIndex").attr("value", ""); } else { $("#searchFrom").attr("action", "@{@Html.Raw(ViewBag.SearchConUrl);}pageIndex=" + indexValue); $("#searchFrom").submit(); } } } //页面加载事件 $(function () { $("#pageLi>ul>li").click(function () { $("#searchFrom").attr("action", "@{@Html.Raw(ViewBag.SearchConUrl);}pageIndex=" + $(this).attr("data-pageIndex")); $("#searchFrom").submit(); }); }); </script>
4.2.2.html布局处理
<div class="box-footer no-padding"> <div class="mailbox-controls"> <div class="pull-right"> <div style="" id="pageLi"> <div style="float:right;"> <span style="float: right; margin: 9px 16px 5px 10px; font-size: 16px">共<font style="font-weight:bolder;">@ViewBag.pageCount</font>页/共<font style="font-weight:bolder;">@(ViewBag.dataCount)</font>条</span> </div> <ul class="pagination" style="margin: 5px;"> <li data-pageIndex="1"> <a href="javascript:void(0);">首页</a> </li> @{ int prev = ViewBag.pageCurren > 1 ? ViewBag.pageCurren - 1 : 1; int next = ViewBag.pageCurren < ViewBag.pageCount ? ViewBag.pageCurren + 1 : ViewBag.pageCount; } <li data-pageIndex="@prev"> <a href="javascript:void(0);">上一页</a> </li> @{ int pageCount = ViewBag.pageCount; int pageCurren = ViewBag.pageCurren; int pageEnd = pageCount < 5 ? pageCount : pageCurren + 2 >= pageCount ? pageCount : pageCurren + 2 >= 5 ? pageCurren + 2 : 5; int pageBegin = pageCount > 5 ? pageEnd > 5 ? pageEnd - 4 : 1 : 1; for (int i = pageBegin; i <= pageEnd; i++) { if (i == pageCurren) { <li data-pageIndex="@i" id="pageCurren"><a href="javascript:void(0);" style="background-color: #428BCA;color:#fff">@i</a></li> } else { string index = "page" + @i; <li data-pageIndex="@i" id="@index"><a href="javascript:void(0);">@i</a></li> } } } <li data-pageIndex="@next"><a href="javascript:void(0);">下一页 </a></li> <li data-pageIndex="@pageCount"><a href="javascript:void(0);">尾页</a></li> </ul> <div class="btn-group" style="float: right; margin:5px;"> <span type="button" style="float: right;background:#428BCA;border-color: #367fa9;border-radius: 3px;" class="btn btn-info btn-sm" id="breakUrl"><strong>GO!</strong></span> <input type="text" class="form-control" placeholder="页码" style="width: 60px;margin-left:3px;height:auto;float: right;font-size: 12px;" id="pageIndex" onchange="ChangeUrl();"> </div> </div> </div> <!-- /.btn-group --> </div> <!-- /.pull-right --> </div>
5.http接口调用帮助类
在项目中封装接口应该是现在项目当中必不可少的一层开发。以下方法是http调用接口的时候封装类,其中调用方法有get,post。返回类型有xml与json
public class HttpHelper { private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; private static string ControllerIp = ""; private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; //总是接受 } public HttpHelper(string ip = "") { if (string.IsNullOrEmpty(ip)) ControllerIp = ConfigurationManager.AppSettings["StrokeInterface"]; else ControllerIp = ip; } #region 返回HttpWebResponse /// <summary> /// Http Get 返回 HttpWebResponse (不处理异常) /// </summary> /// <param name="url">请求的URL</param> /// <param name="parameters">请求参数(可以为null)</param> /// <param name="timeout">请求的超时时间(可选参数)</param> /// <param name="userAgent">请求的客户端浏览器信息(可以为null)</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息(可以为null)</param> /// <param name="resEncoding">结果编码(可以为null,默认utf-8)</param> /// <returns></returns> public HttpWebResponse HttpGet(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, CookieCollection cookies, Encoding resEncoding) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } url = ControllerIp + url; if (resEncoding == null) { resEncoding = Encoding.UTF8; } if (!(parameters == null || parameters.Count == 0)) { url = url + "?" + GetGetPara(parameters); } HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; request.UserAgent = DefaultUserAgent; if (!string.IsNullOrEmpty(userAgent)) { request.UserAgent = userAgent; } if (timeout.HasValue) { request.Timeout = timeout.Value; } if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } return request.GetResponse() as HttpWebResponse; } /// <summary> /// Https Get 返回 HttpWebResponse (不处理异常) /// </summary> /// <param name="url">请求的URL</param> /// <param name="parameters">请求参数(可以为null)</param> /// <param name="timeout">请求的超时时间(可选参数)</param> /// <param name="userAgent">请求的客户端浏览器信息(可以为null)</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息(可以为null)</param> /// <param name="resEncoding">结果编码(可以为null,默认utf-8)</param> /// <returns></returns> public HttpWebResponse HttpsGet(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, CookieCollection cookies, Encoding resEncoding) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } url = ControllerIp + url; if (resEncoding == null) { resEncoding = Encoding.UTF8; } if (!(parameters == null || parameters.Count == 0)) { url = url + "?" + GetGetPara(parameters); } HttpWebRequest request = null; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10; request.Method = "GET"; request.UserAgent = DefaultUserAgent; if (!string.IsNullOrEmpty(userAgent)) { request.UserAgent = userAgent; } if (timeout.HasValue) { request.Timeout = timeout.Value; } if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } return request.GetResponse() as HttpWebResponse; } /// <summary> /// Http Post 返回 HttpWebResponse (不处理异常) /// </summary> /// <param name="url">请求的URL</param> /// <param name="parameters">请求参数(可以为null)</param> /// <param name="timeout">请求的超时时间(可选参数)</param> /// <param name="userAgent">请求的客户端浏览器信息(可以为null)</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息(可以为null)</param> /// <param name="reqEncoding">请求编码(可以为null,默认utf-8)</param> /// <param name="resEncoding">结果编码(可以为null,默认utf-8)</param> /// <returns></returns> public HttpWebResponse HttpPost(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, CookieCollection cookies, Encoding reqEncoding, Encoding resEncoding) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } url = ControllerIp + url; if (reqEncoding == null) { reqEncoding = Encoding.UTF8; } if (resEncoding == null) { resEncoding = Encoding.UTF8; } HttpWebRequest request = null; request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; if (!string.IsNullOrEmpty(userAgent)) { request.UserAgent = userAgent; } else { request.UserAgent = DefaultUserAgent; } if (timeout.HasValue) { request.Timeout = timeout.Value; } if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } //如果需要POST数据 if (!(parameters == null || parameters.Count == 0)) { byte[] data = GetPostPara(parameters, reqEncoding); using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } } return request.GetResponse() as HttpWebResponse; } /// <summary> /// Https Post 返回 HttpWebResponse (不处理异常) /// </summary> /// <param name="url">请求的URL</param> /// <param name="parameters">请求参数(可以为null)</param> /// <param name="timeout">请求的超时时间(可选参数)</param> /// <param name="userAgent">请求的客户端浏览器信息(可以为null)</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息(可以为null)</param> /// <param name="reqEncoding">请求编码(可以为null,默认utf-8)</param> /// <param name="resEncoding">结果编码(可以为null,默认utf-8)</param> /// <returns></returns> public HttpWebResponse HttpsPost(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, CookieCollection cookies, Encoding reqEncoding, Encoding resEncoding) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } url = ControllerIp + url; if (reqEncoding == null) { reqEncoding = Encoding.UTF8; } if (resEncoding == null) { resEncoding = Encoding.UTF8; } HttpWebRequest request = null; //如果是发送HTTPS请求 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; if (!string.IsNullOrEmpty(userAgent)) { request.UserAgent = userAgent; } else { request.UserAgent = DefaultUserAgent; } if (timeout.HasValue) { request.Timeout = timeout.Value; } if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } //如果需要POST数据 if (!(parameters == null || parameters.Count == 0)) { byte[] data = GetPostPara(parameters, reqEncoding); using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } } return request.GetResponse() as HttpWebResponse; } #endregion #region 返回String /// <summary> /// Http Get 返回 String (异常返回null) /// </summary> /// <param name="url">请求的URL</param> /// <param name="parameters">请求参数(可以为null)</param> /// <param name="timeout">请求的超时时间(可选参数)</param> /// <param name="userAgent">请求的客户端浏览器信息(可以为null)</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息(可以为null)</param> /// <param name="resEncoding">结果编码(可以为null,默认utf-8)</param> /// <returns></returns> public string HttpGetString(string url, IDictionary<string, string> parameters, int? timeout = null, string userAgent="", CookieCollection cookies=null, Encoding resEncoding=null) { try { if (resEncoding == null) { resEncoding = Encoding.UTF8; } HttpWebResponse hwr = HttpGet(url, parameters, timeout, userAgent, cookies, resEncoding); return GetResString(hwr, resEncoding); } catch (Exception ex) { return null; } } /// <summary> /// Https Get 返回 String (异常返回null) /// </summary> /// <param name="url">请求的URL</param> /// <param name="parameters">请求参数(可以为null)</param> /// <param name="timeout">请求的超时时间(可选参数)</param> /// <param name="userAgent">请求的客户端浏览器信息(可以为null)</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息(可以为null)</param> /// <param name="resEncoding">结果编码(可以为null,默认utf-8)</param> /// <returns></returns> public string HttpsGetString(string url, IDictionary<string, string> parameters, int? timeout = null, string userAgent="", CookieCollection cookies=null, Encoding resEncoding=null) { try { if (resEncoding == null) { resEncoding = Encoding.UTF8; } HttpWebResponse hwr = HttpsGet(url, parameters, timeout, userAgent, cookies, resEncoding); return GetResString(hwr, resEncoding); } catch (Exception ex) { return null; } } /// <summary> /// Http Post 返回 String (异常返回null) /// </summary> /// <param name="url">请求的URL</param> /// <param name="parameters">请求参数(可以为null)</param> /// <param name="timeout">请求的超时时间(可选参数)</param> /// <param name="userAgent">请求的客户端浏览器信息(可以为null)</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息(可以为null)</param> /// <param name="reqEncoding">请求编码(可以为null,默认utf-8)</param> /// <param name="resEncoding">结果编码(可以为null,默认utf-8)</param> /// <returns></returns> public string HttpPostString(string url, IDictionary<string, string> parameters, int? timeout=null, string userAgent="", CookieCollection cookies=null, Encoding reqEncoding=null, Encoding resEncoding=null) { try { if (reqEncoding == null) { reqEncoding = Encoding.UTF8; } if (resEncoding == null) { resEncoding = Encoding.UTF8; } HttpWebResponse hwr = HttpPost(url, parameters, timeout, userAgent, cookies, reqEncoding, resEncoding); return GetResString(hwr, resEncoding); } catch (Exception ex) { return null; } } /// <summary> /// Https Post 返回 String (异常返回null) /// </summary> /// <param name="url">请求的URL</param> /// <param name="parameters">请求参数(可以为null)</param> /// <param name="timeout">请求的超时时间(可选参数)</param> /// <param name="userAgent">请求的客户端浏览器信息(可以为null)</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息(可以为null)</param> /// <param name="reqEncoding">请求编码(可以为null,默认utf-8)</param> /// <param name="resEncoding">结果编码(可以为null,默认utf-8)</param> /// <returns></returns> public string HttpsPostString(string url, IDictionary<string, string> parameters, int? timeout = null, string userAgent="", CookieCollection cookies=null, Encoding reqEncoding=null, Encoding resEncoding=null) { try { if (reqEncoding == null) { reqEncoding = Encoding.UTF8; } if (resEncoding == null) { resEncoding = Encoding.UTF8; } HttpWebResponse hwr = HttpsPost(url, parameters, timeout, userAgent, cookies, reqEncoding, resEncoding); return GetResString(hwr, resEncoding); } catch (Exception ex) { return null; } } #endregion #region 返回Json /// <summary> /// Http Get 返回 Json (异常返回null) /// </summary> /// <param name="url">请求的URL</param> /// <param name="parameters">请求参数(可以为null)</param> /// <param name="timeout">请求的超时时间(可选参数)</param> /// <param name="userAgent">请求的客户端浏览器信息(可以为null)</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息(可以为null)</param> /// <param name="resEncoding">结果编码(可以为null,默认utf-8)</param> /// <returns></returns> public JObject HttpGetJson(string url, IDictionary<string, string> parameters, int? timeout = null, string userAgent="", CookieCollection cookies=null, Encoding resEncoding=null) { try { if (resEncoding == null) { resEncoding = Encoding.UTF8; } HttpWebResponse hwr = HttpGet(url, parameters, timeout, userAgent, cookies, resEncoding); return GetResJson(hwr, resEncoding); } catch (Exception ex) { return null; } } /// <summary> /// Https Get 返回 Json (异常返回null) /// </summary> /// <param name="url">请求的URL</param> /// <param name="parameters">请求参数(可以为null)</param> /// <param name="timeout">请求的超时时间(可选参数)</param> /// <param name="userAgent">请求的客户端浏览器信息(可以为null)</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息(可以为null)</param> /// <param name="resEncoding">结果编码(可以为null,默认utf-8)</param> /// <returns></returns> public JObject HttpsGetJson(string url, IDictionary<string, string> parameters, int? timeout = null, string userAgent="", CookieCollection cookies=null, Encoding resEncoding=null) { try { if (resEncoding == null) { resEncoding = Encoding.UTF8; } HttpWebResponse hwr = HttpsGet(url, parameters, timeout, userAgent, cookies, resEncoding); return GetResJson(hwr, resEncoding); } catch (Exception ex) { return null; } } /// <summary> /// Http Post 返回 Json (异常返回null) /// </summary> /// <param name="url">请求的URL</param> /// <param name="parameters">请求参数(可以为null)</param> /// <param name="timeout">请求的超时时间(可选参数)</param> /// <param name="userAgent">请求的客户端浏览器信息(可以为null)</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息(可以为null)</param> /// <param name="reqEncoding">请求编码(可以为null,默认utf-8)</param> /// <param name="resEncoding">结果编码(可以为null,默认utf-8)</param> /// <returns></returns> public JObject HttpPostJson(string url, IDictionary<string, string> parameters, int? timeout = null, string userAgent="", CookieCollection cookies=null, Encoding reqEncoding=null, Encoding resEncoding=null) { try { if (reqEncoding == null) { reqEncoding = Encoding.UTF8; } if (resEncoding == null) { resEncoding = Encoding.UTF8; } HttpWebResponse hwr = HttpPost(url, parameters, timeout, userAgent, cookies, reqEncoding, resEncoding); return GetResJson(hwr, resEncoding); } catch (Exception ex) { return null; } } /// <summary> /// Https Post 返回 Json (异常返回null) /// </summary> /// <param name="url">请求的URL</param> /// <param name="parameters">请求参数(可以为null)</param> /// <param name="timeout">请求的超时时间(可选参数)</param> /// <param name="userAgent">请求的客户端浏览器信息(可以为null)</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息(可以为null)</param> /// <param name="reqEncoding">请求编码(可以为null,默认utf-8)</param> /// <param name="resEncoding">结果编码(可以为null,默认utf-8)</param> /// <returns></returns> public JObject HttpsPostJson(string url, IDictionary<string, string> parameters, int? timeout = null, string userAgent="", CookieCollection cookies=null, Encoding reqEncoding=null, Encoding resEncoding=null) { try { if (reqEncoding == null) { reqEncoding = Encoding.UTF8; } if (resEncoding == null) { resEncoding = Encoding.UTF8; } HttpWebResponse hwr = HttpsPost(url, parameters, timeout, userAgent, cookies, reqEncoding, resEncoding); return GetResJson(hwr, resEncoding); } catch (Exception ex) { return null; } } #endregion #region 返回XML /// <summary> /// Http Get 返回 Xml (异常返回null) /// </summary> /// <param name="url">请求的URL</param> /// <param name="parameters">请求参数(可以为null)</param> /// <param name="timeout">请求的超时时间(可选参数)</param> /// <param name="userAgent">请求的客户端浏览器信息(可以为null)</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息(可以为null)</param> /// <param name="resEncoding">结果编码(可以为null,默认utf-8)</param> /// <returns></returns> public XmlDocument HttpGetXml(string url, IDictionary<string, string> parameters, int? timeout = null, string userAgent="", CookieCollection cookies=null, Encoding resEncoding=null) { try { if (resEncoding == null) { resEncoding = Encoding.UTF8; } HttpWebResponse hwr = HttpGet(url, parameters, timeout, userAgent, cookies, resEncoding); return GetResXml(hwr, resEncoding); } catch (Exception ex) { return null; } } /// <summary> /// Https Get 返回 Xml (异常返回null) /// </summary> /// <param name="url">请求的URL</param> /// <param name="parameters">请求参数(可以为null)</param> /// <param name="timeout">请求的超时时间(可选参数)</param> /// <param name="userAgent">请求的客户端浏览器信息(可以为null)</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息(可以为null)</param> /// <param name="resEncoding">结果编码(可以为null,默认utf-8)</param> /// <returns></returns> public XmlDocument HttpsGetXml(string url, IDictionary<string, string> parameters, int? timeout = null, string userAgent="", CookieCollection cookies=null, Encoding resEncoding=null) { try { if (resEncoding == null) { resEncoding = Encoding.UTF8; } HttpWebResponse hwr = HttpsGet(url, parameters, timeout, userAgent, cookies, resEncoding); return GetResXml(hwr, resEncoding); } catch (Exception ex) { return null; } } /// <summary> /// Http Post 返回 Xml (异常返回null) /// </summary> /// <param name="url">请求的URL</param> /// <param name="parameters">请求参数(可以为null)</param> /// <param name="timeout">请求的超时时间(可选参数)</param> /// <param name="userAgent">请求的客户端浏览器信息(可以为null)</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息(可以为null)</param> /// <param name="reqEncoding">请求编码(可以为null,默认utf-8)</param> /// <param name="resEncoding">结果编码(可以为null,默认utf-8)</param> /// <returns></returns> public XmlDocument HttpPostXml(string url, IDictionary<string, string> parameters, int? timeout=null, string userAgent="", CookieCollection cookies=null, Encoding reqEncoding=null, Encoding resEncoding=null) { try { if (reqEncoding == null) { reqEncoding = Encoding.UTF8; } if (resEncoding == null) { resEncoding = Encoding.UTF8; } HttpWebResponse hwr = HttpPost(url, parameters, timeout, userAgent, cookies, reqEncoding, resEncoding); return GetResXml(hwr, resEncoding); } catch (Exception ex) { return null; } } /// <summary> /// Https Post 返回 Xml (异常返回null) /// </summary> /// <param name="url">请求的URL</param> /// <param name="parameters">请求参数(可以为null)</param> /// <param name="timeout">请求的超时时间(可选参数)</param> /// <param name="userAgent">请求的客户端浏览器信息(可以为null)</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息(可以为null)</param> /// <param name="reqEncoding">请求编码(可以为null,默认utf-8)</param> /// <param name="resEncoding">结果编码(可以为null,默认utf-8)</param> /// <returns></returns> public XmlDocument HttpsPostXml(string url, IDictionary<string, string> parameters, int? timeout = null, string userAgent="", CookieCollection cookies=null, Encoding reqEncoding=null, Encoding resEncoding=null) { try { if (reqEncoding == null) { reqEncoding = Encoding.UTF8; } if (resEncoding == null) { resEncoding = Encoding.UTF8; } HttpWebResponse hwr = HttpsPost(url, parameters, timeout, userAgent, cookies, reqEncoding, resEncoding); return GetResXml(hwr, resEncoding); } catch (Exception ex) { return null; } } #endregion #region 返回结果处理 /// <summary> /// 处理返回结果 /// </summary> /// <param name="hwr"></param> /// <returns></returns> private string GetResString(HttpWebResponse hwr, Encoding resEncoding) { if (hwr.StatusCode == HttpStatusCode.OK) { Stream receiveStream = hwr.GetResponseStream(); StreamReader readStream = new StreamReader(receiveStream, resEncoding); string str = readStream.ReadToEnd(); hwr.Close(); receiveStream.Close(); readStream.Close(); return str; } else { return null; } } /// <summary> /// 处理返回结果 /// </summary> /// <param name="hwr"></param> /// <returns></returns> private JObject GetResJson(HttpWebResponse hwr, Encoding resEncoding) { if (hwr.StatusCode == HttpStatusCode.OK) { Stream receiveStream = hwr.GetResponseStream(); StreamReader readStream = new StreamReader(receiveStream, resEncoding); string r = readStream.ReadToEnd(); hwr.Close(); receiveStream.Close(); readStream.Close(); if (string.IsNullOrEmpty(r)) { return null; } else { return JObject.Parse(r); } } else { return null; } } /// <summary> /// 处理返回结果 /// </summary> /// <param name="hwr"></param> /// <returns></returns> private XmlDocument GetResXml(HttpWebResponse hwr, Encoding resEncoding) { if (hwr.StatusCode == HttpStatusCode.OK) { Stream receiveStream = hwr.GetResponseStream(); StreamReader readStream = new StreamReader(receiveStream, resEncoding); string r = readStream.ReadToEnd(); hwr.Close(); receiveStream.Close(); readStream.Close(); if (string.IsNullOrEmpty(r)) { return null; } else { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(r); return xmlDoc; } } else { return null; } } #endregion #region 请求参数处理 /// <summary> /// 处理POST参数 /// </summary> /// <param name="parameters"></param> /// <param name="reqEncoding"></param> /// <returns></returns> public byte[] GetPostPara(IDictionary<string, string> parameters, Encoding reqEncoding) { if (reqEncoding == null) { reqEncoding = Encoding.UTF8; } StringBuilder buffer = new StringBuilder(); int i = 0; foreach (string key in parameters.Keys) { if (i > 0) { buffer.AppendFormat("&{0}={1}", key, parameters[key]); } else { buffer.AppendFormat("{0}={1}", key, parameters[key]); } i++; } return reqEncoding.GetBytes(buffer.ToString()); } /// <summary> /// 处理get参数 /// </summary> /// <param name="parameters"></param> /// <returns></returns> public string GetGetPara(IDictionary<string, string> parameters) { StringBuilder buffer = new StringBuilder(); int i = 0; foreach (string key in parameters.Keys) { if (i > 0) { buffer.AppendFormat("&{0}={1}", key, Microsoft.JScript.GlobalObject.escape(parameters[key])); } else { buffer.AppendFormat("{0}={1}", key, Microsoft.JScript.GlobalObject.escape(parameters[key])); } i++; } return buffer.ToString(); } #endregion }
6.获取配置(webconfig,appconfig)文件内容
public enum ConfigurationFile { AppConfig = 1, WebConfig = 2 } /// <summary> /// ConfigManager 应用程序配置文件管理器 /// </summary> public class ConfigManager { public ConfigManager() { // // TODO: 在此处添加构造函数逻辑 // } /// <summary> /// 对[appSettings]节点依据Key值读取到Value值,返回字符串 /// </summary> /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param> /// <param name="key">要读取的Key值</param> /// <returns>返回Value值的字符串</returns> public static string ReadValueByKey(ConfigurationFile configurationFile, string key) { string value = string.Empty; string filename = string.Empty; if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString()) { filename = System.Windows.Forms.Application.ExecutablePath + ".config"; } else { filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config"; } XmlDocument doc = new XmlDocument(); doc.Load(filename); //加载配置文件 XmlNode node = doc.SelectSingleNode("//appSettings"); //得到[appSettings]节点 ////得到[appSettings]节点中关于Key的子节点 XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key=‘" + key + "‘]"); if (element != null) { value = element.GetAttribute("value"); } return value; } /// <summary> /// 对[connectionStrings]节点依据name值读取到connectionString值,返回字符串 /// </summary> /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param> /// <param name="name">要读取的name值</param> /// <returns>返回connectionString值的字符串</returns> public static string ReadConnectionStringByName(ConfigurationFile configurationFile, string name) { string connectionString = string.Empty; string filename = string.Empty; if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString()) { filename = System.Windows.Forms.Application.ExecutablePath + ".config"; } else { filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config"; } XmlDocument doc = new XmlDocument(); doc.Load(filename); //加载配置文件 XmlNode node = doc.SelectSingleNode("//connectionStrings"); //得到[appSettings]节点 ////得到[connectionString]节点中关于name的子节点 XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name=‘" + name + "‘]"); if (element != null) { connectionString = element.GetAttribute("connectionString"); } return connectionString; } /// <summary> /// 更新或新增[appSettings]节点的子节点值,存在则更新子节点Value,不存在则新增子节点,返回成功与否布尔值 /// </summary> /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param> /// <param name="key">子节点Key值</param> /// <param name="value">子节点value值</param> /// <returns>返回成功与否布尔值</returns> public static bool UpdateOrCreateAppSetting(ConfigurationFile configurationFile, string key, string value) { bool isSuccess = false; string filename = string.Empty; if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString()) { filename = System.Windows.Forms.Application.ExecutablePath + ".config"; } else { filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config"; } XmlDocument doc = new XmlDocument(); doc.Load(filename); //加载配置文件 XmlNode node = doc.SelectSingleNode("//appSettings"); //得到[appSettings]节点 try { ////得到[appSettings]节点中关于Key的子节点 XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key=‘" + key + "‘]"); if (element != null) { //存在则更新子节点Value element.SetAttribute("value", value); } else { //不存在则新增子节点 XmlElement subElement = doc.CreateElement("add"); subElement.SetAttribute("key", key); subElement.SetAttribute("value", value); node.AppendChild(subElement); } //保存至配置文件(方式一) using (XmlTextWriter xmlwriter = new XmlTextWriter(filename, null)) { xmlwriter.Formatting = Formatting.Indented; doc.WriteTo(xmlwriter); xmlwriter.Flush(); } isSuccess = true; } catch (Exception ex) { isSuccess = false; throw ex; } return isSuccess; } /// <summary> /// 更新或新增[connectionStrings]节点的子节点值,存在则更新子节点,不存在则新增子节点,返回成功与否布尔值 /// </summary> /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param> /// <param name="name">子节点name值</param> /// <param name="connectionString">子节点connectionString值</param> /// <param name="providerName">子节点providerName值</param> /// <returns>返回成功与否布尔值</returns> public static bool UpdateOrCreateConnectionString(ConfigurationFile configurationFile, string name, string connectionString, string providerName) { bool isSuccess = false; string filename = string.Empty; if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString()) { filename = System.Windows.Forms.Application.ExecutablePath + ".config"; } else { filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config"; } XmlDocument doc = new XmlDocument(); doc.Load(filename); //加载配置文件 XmlNode node = doc.SelectSingleNode("//connectionStrings"); //得到[connectionStrings]节点 try { ////得到[connectionStrings]节点中关于Name的子节点 XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name=‘" + name + "‘]"); if (element != null) { //存在则更新子节点 element.SetAttribute("connectionString", connectionString); element.SetAttribute("providerName", providerName); } else { //不存在则新增子节点 XmlElement subElement = doc.CreateElement("add"); subElement.SetAttribute("name", name); subElement.SetAttribute("connectionString", connectionString); subElement.SetAttribute("providerName", providerName); node.AppendChild(subElement); } //保存至配置文件(方式二) doc.Save(filename); isSuccess = true; } catch (Exception ex) { isSuccess = false; throw ex; } return isSuccess; } /// <summary> /// 删除[appSettings]节点中包含Key值的子节点,返回成功与否布尔值 /// </summary> /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param> /// <param name="key">要删除的子节点Key值</param> /// <returns>返回成功与否布尔值</returns> public static bool DeleteByKey(ConfigurationFile configurationFile, string key) { bool isSuccess = false; string filename = string.Empty; if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString()) { filename = System.Windows.Forms.Application.ExecutablePath + ".config"; } else { filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config"; } XmlDocument doc = new XmlDocument(); doc.Load(filename); //加载配置文件 XmlNode node = doc.SelectSingleNode("//appSettings"); //得到[appSettings]节点 ////得到[appSettings]节点中关于Key的子节点 XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key=‘" + key + "‘]"); if (element != null) { //存在则删除子节点 element.ParentNode.RemoveChild(element); } else { //不存在 } try { //保存至配置文件(方式一) using (XmlTextWriter xmlwriter = new XmlTextWriter(filename, null)) { xmlwriter.Formatting = Formatting.Indented; doc.WriteTo(xmlwriter); xmlwriter.Flush(); } isSuccess = true; } catch (Exception ex) { isSuccess = false; } return isSuccess; } /// <summary> /// 删除[connectionStrings]节点中包含name值的子节点,返回成功与否布尔值 /// </summary> /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param> /// <param name="name">要删除的子节点name值</param> /// <returns>返回成功与否布尔值</returns> public static bool DeleteByName(ConfigurationFile configurationFile, string name) { bool isSuccess = false; string filename = string.Empty; if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString()) { filename = System.Windows.Forms.Application.ExecutablePath + ".config"; } else { filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config"; } XmlDocument doc = new XmlDocument(); doc.Load(filename); //加载配置文件 XmlNode node = doc.SelectSingleNode("//connectionStrings"); //得到[connectionStrings]节点 ////得到[connectionStrings]节点中关于Name的子节点 XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name=‘" + name + "‘]"); if (element != null) { //存在则删除子节点 node.RemoveChild(element); } else { //不存在 } try { //保存至配置文件(方式二) doc.Save(filename); isSuccess = true; } catch (Exception ex) { isSuccess = false; } return isSuccess; } }
7.数据验证
身份证,手机号,邮件。。。。。但是我都是在前台进行判断,但是就先留着吧。
public class ValidateHelper { /// <summary> /// 验证电话号码 /// </summary> /// <param name="txt"></param> /// <returns></returns> public static string ValidateTel(string txt) { if (String.IsNullOrEmpty(txt)) return "请输入座机号码!"; bool b = Regex.IsMatch(txt, @"^((\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1})|(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1}))$"); if (!b) return "座机号码格式错误!"; return ""; } /// <summary> /// 验证网址 /// </summary> /// <param name="txt"></param> /// <returns></returns> public static string ValidateURL(string txt) { if (String.IsNullOrEmpty(txt)) return "请输入网址!"; bool b = Regex.IsMatch(txt, @"^((http|https)://)?(www.)?[a-z0-9\\.]+(\\.(com|net|cn|com\\.cn|com\\.net|net\\.cn))(/[^\\s\\n]*)?$"); if (!b) return "网址格式错误!"; return ""; } /// <summary> /// 验证手机号码 /// </summary> /// <param name="txt"></param> /// <returns></returns> public static string ValidatePhone(string txt) { if (String.IsNullOrEmpty(txt)) return "请输入手机号码!"; bool b = Regex.IsMatch(txt, @"^1[3,4,5,7,8]\\d{9}"); if (!b) return "手机号码格式错误!"; return ""; } /// <summary> /// 验证邮编 /// </summary> /// <param name="txt"></param> /// <returns></returns> public static string ValidateZIP(string txt) { if (String.IsNullOrEmpty(txt)) return "请输入邮编!"; bool b = Regex.IsMatch(txt, @"^[1-9]\\d{5}$"); if (!b) return "邮编格式错误!"; return ""; } /// <summary> /// 验证邮箱 /// </summary> /// <param name="txt"></param> /// <returns></returns> public static string ValidateEmail(string txt) { if (String.IsNullOrEmpty(txt)) return "请输入邮箱账号!"; bool b = Regex.IsMatch(txt, @"^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$"); if (!b) return "邮箱格式错误!"; return ""; } /// <summary> /// 18位身份证号码验证 /// </summary> /// <param name="card">身份证号码</param> /// <returns>Error:格式错误 "":格式正确</returns> public static string CheckIDCard18(string card) { if (String.IsNullOrEmpty(card)) return "请输入身份证号码!"; if (card.Length != 18) return "身份证号码格式错误!"; if (!Regex.IsMatch(card, @"^\\d{17}(\\d|X|x)$")) return "身份证号码格式错误!"; long n = 0; if (long.TryParse(card.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(card.Replace(‘x‘, ‘0‘).Replace(‘X‘, ‘0‘), out n) == false) { return "身份证号码格式错误!"; } string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91"; if (address.IndexOf(card.Remove(2)) == -1) { return "身份证号码格式错误!";// "省份验证"; } string birth = card.Substring(6, 8).Insert(6, "-").Insert(4, "-"); DateTime time = new DateTime(); if (DateTime.TryParse(birth, out time) == false) { return "身份证号码格式错误!";//"生日验证"; } string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(‘,‘); string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(‘,‘); char[] Ai = card.Remove(17).ToCharArray(); int sum = 0; for (int i = 0; i < 17; i++) { sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString()); } int y = -1; Math.DivRem(sum, 11, out y); if (arrVarifyCode[y] != card.Substring(17, 1).ToLower()) { return "身份证号码格式错误!";//校验码验证 } //return card;//符合GB11643-1999标准 return ""; } }
8.文件检测
项目中有一个这样的需求:当文档中的文件有一个文件进行了更改,这时要获取这个文件的内容,该怎么处理的,这个需求当时就想用事件进行处理,但搜索了一下,发现原来本身c#就有这样的事件监测。代码如下:
public class FileSystemWatcherHelper { private FileSystemWatcher watcher; ILogger logger = new Logger4Net("readFiles"); public void OnStart() { if (watcher == null) { watcher = new System.IO.FileSystemWatcher(); watcher.Path = ReadFiles.GetPath(); watcher.IncludeSubdirectories = true; //watcher.Filter = "*.dat"; watcher.Created += new FileSystemEventHandler(OnFileCreated); watcher.EnableRaisingEvents = true; } } /// <summary> /// 暂停监测 /// </summary> public void OnStop() { // TODO: 在此处添加代码以执行停止服务所需的关闭操作。 if (watcher != null) { watcher.EnableRaisingEvents = false; watcher.Dispose(); } } /// <summary> /// 监测到新文件的处理程序 /// </summary> /// <param name="source"></param> /// <param name="e"></param> public void OnFileCreated(Object source, FileSystemEventArgs e) { logger.Trace("开始执行读取文件"+ e.FullPath); if (File.Exists(e.FullPath)) { //解析新增加的文件 ReadFiles.ReadFile(e.FullPath); } } } }
9.读取文件
在项目中读取一个不断变动的文件,把数据导入数据库,这就是下面这个类的内容,和上面文件检测结合,就会有一个不错的业务流程。
public class FileSystemWatcherHelper { private FileSystemWatcher watcher; ILogger logger = new Logger4Net("readFiles"); public void OnStart() { if (watcher == null) { watcher = new System.IO.FileSystemWatcher(); watcher.Path = ReadFiles.GetPath(); watcher.IncludeSubdirectories = true; //watcher.Filter = "*.dat"; watcher.Created += new FileSystemEventHandler(OnFileCreated); watcher.EnableRaisingEvents = true; } } /// <summary> /// 暂停监测 /// </summary> public void OnStop() { // TODO: 在此处添加代码以执行停止服务所需的关闭操作。 if (watcher != null) { watcher.EnableRaisingEvents = false; watcher.Dispose(); } } /// <summary> /// 监测到新文件的处理程序 /// </summary> /// <param name="source"></param> /// <param name="e"></param> public void OnFileCreated(Object source, FileSystemEventArgs e) { logger.Trace("开始执行读取文件"+ e.FullPath); if (File.Exists(e.FullPath)) { //解析新增加的文件 ReadFiles.ReadFile(e.FullPath); } } } }
10.文件(夹)压缩解压操作
public class ZipFileControl { #region 压缩文件夹,支持递归 /// <summary> /// 压缩文件夹 /// </summary> /// <param name="dir">待压缩的文件夹</param> /// <param name="targetFileName">压缩后文件路径(包括文件名)</param> /// <param name="recursive">是否递归压缩</param> /// <returns></returns> public bool Compress(string dir, string targetFileName, bool recursive) { //如果已经存在目标文件,询问用户是否覆盖 if (File.Exists(targetFileName)) { // if (!_ProcessOverwrite(targetFileName)) return false; } string[] ars = new string[2]; if (recursive == false) { //return Compress(dir, targetFileName); ars[0] = dir; ars[1] = targetFileName; return ZipFileDictory(ars); } FileStream ZipFile; ZipOutputStream ZipStream; //open ZipFile = File.Create(targetFileName); ZipStream = new ZipOutputStream(ZipFile); if (dir != String.Empty) { _CompressFolder(dir, ZipStream, dir); } //close ZipStream.Finish(); ZipStream.Close(); if (File.Exists(targetFileName)) return true; else return false; } /// <summary> /// 压缩目录 /// </summary> /// <param name="args">数组(数组[0]: 要压缩的目录; 数组[1]: 压缩的文件名)</param> public static bool ZipFileDictory(string[] args) { ZipOutputStream s = null; try { string[] filenames = Directory.GetFiles(args[0]); Crc32 crc = new Crc32(); s = new ZipOutputStream(File.Create(args[1])); s.SetLevel(6); foreach (string file in filenames) { //打开压缩文件 FileStream fs = File.OpenRead(file); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); ZipEntry entry = new ZipEntry(file); entry.DateTime = DateTime.Now; entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } } catch (Exception e) { return false; } finally { s.Finish(); s.Close(); } return true; } /// <summary> /// 压缩某个子文件夹 /// </summary> /// <param name="basePath"></param> /// <param name="zips"></param> /// <param name="zipfolername"></param> private static void _CompressFolder(string basePath, ZipOutputStream zips, string zipfolername) { if (File.Exists(basePath)) { _AddFile(basePath, zips, zipfolername); return; } string[] names = Directory.GetFiles(basePath); foreach (string fileName in names) { _AddFile(fileName, zips, zipfolername); } names = Directory.GetDirectories(basePath); foreach (string folderName in names) { _CompressFolder(folderName, zips, zipfolername); } } /// <summary> /// 压缩某个子文件 /// </summary> /// <param name="fileName"></param> /// <param name="zips"></param> /// <param name="zipfolername"></param> private static void _AddFile(string fileName, ZipOutputStream zips, string zipfolername) { if (File.Exists(fileName)) { _CreateZipFile(fileName, zips, zipfolername); } } /// <summary> /// 压缩单独文件 /// </summary> /// <param name="FileToZip"></param> /// <param name="zips"></param> /// <param name="zipfolername"></param> private static void _CreateZipFile(string FileToZip, ZipOutputStream zips, string zipfolername) { try { FileStream StreamToZip = new FileStream(FileToZip, FileMode.Open, FileAccess.Read); string temp = FileToZip; string temp1 = zipfolername; if (temp1.Length > 0) { int i = temp1.LastIndexOf(‘\\\\‘) + 1; int j = temp.Length - i; temp = temp.Substring(i, j); } ZipEntry ZipEn = new ZipEntry(temp); zips.PutNextEntry(ZipEn); byte[] buffer = new byte[16384]; System.Int32 size = StreamToZip.Read(buffer, 0, buffer.Length); zips.Write(buffer, 0, size); try { while (size < StreamToZip.Length) { int sizeRead = StreamToZip.Read(buffer, 0, buffer.Length); zips.Write(buffer, 0, sizeRead); size += sizeRead; } } catch (System.Exception ex) { throw ex; } StreamToZip.Close(); } catch (Exception e) { throw e; } } #endregion #region 解压zip格式的文件。 /// <summary> /// 功能:解压zip格式的文件。(该方法用于卒中专项培训课件解压) /// </summary> /// <param name="zipFilePath">压缩文件路径</param> /// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param> /// <param name="fileNameUpd"></param> /// <returns></returns> public bool UnZipFile_PX(string zipFilePath, string unZipDir) { string err = ""; if (zipFilePath == string.Empty) { err = "压缩文件不能为空!"; return false; } if (!File.Exists(zipFilePath)) { err = "压缩文件不存在!"; return false; } //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹 if (unZipDir == string.Empty) unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath)); if (!unZipDir.EndsWith("\\\\")) unZipDir += "\\\\"; if (!Directory.Exists(unZipDir)) Directory.CreateDirectory(unZipDir); try { using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath))) { ZipEntry theEntry; string newfile = ""; string fileType = ""; Random r = new Random(); string fileHead = DateTime.Now.ToString("yyyyMMddHHmmss") + r.Next(1000, 9999).ToString(); string str = "000000000"; while ((theEntry = s.GetNextEntry()) != null) { string fileName = Path.GetFileName(theEntry.Name); if (fileName != String.Empty) { int indexType = theEntry.Name.IndexOf("."); fileType = theEntry.Name.Substring(indexType); // newfile = str.Substring(0, (4 - newfile.Length)) + newfile; int indexflag = theEntry.Name.IndexOf("幻灯片"); newfile = theEntry.Name.Substring(0, theEntry.Name.Length - 4); newfile = newfile.Substring(indexflag + 3); newfile = fileHead + (str.Substring(0, (4 - newfile.Length)) + newfile) + fileType; using (FileStream streamWriter = File.Create(unZipDir + newfile)) { int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } } } } } } catch (Exception ex) { err = ex.Message; return false; } return true; } //<summary> //功能:解压zip格式的文件。 //</summary> //<param name="zipFilePath">压缩文件路径</param> //<param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param> //<param name="err">出错信息</param> //<returns>解压是否成功</returns> public bool UnZipFile(string zipFilePath, string unZipDir) { string err = ""; if (zipFilePath == string.Empty) { err = "压缩文件不能为空!"; return false; } if (!File.Exists(zipFilePath)) { err = "压缩文件不存在!"; return false; } //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹 if (unZipDir == string.Empty) unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath)); if (!unZipDir.EndsWith("\\\\")) unZipDir += "\\\\"; if (!Directory.Exists(unZipDir)) Directory.CreateDirectory(unZipDir); try { using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath))) { ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { //string directoryName = Path.GetDirectoryName(theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); //if (directoryName.Length > 0) //{ // Directory.CreateDirectory(unZipDir + directoryName); //} //if (!directoryName.EndsWith("\\\\")) // directoryName += "\\\\"; if (fileName != String.Empty) { //4位 int indexflag=theEntry.Name.IndexOf("幻灯片"); string newfile = theEntry.Name.Substring(0, theEntry.Name.Length - 4); newfile = newfile.Substring(indexflag+3); string str = "000000000"; newfile = str.Substring(0,(4-newfile.Length)) + newfile; Random r = new Random(); string random = r.Next(1000, 9999).ToString(); newfile = DateTime.Now.ToString("yyyyMMddHHmmss") + random + newfile+".JPG"; using (FileStream streamWriter = File.Create(unZipDir + newfile)) { int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } } } } } } catch (Exception ex) { err = ex.Message; return false; } return true; }//解压结束 #endregion #region 获取指定文件夹下所有的文件名称 /// <summary> /// 获取指定文件夹下所有的文件名称 /// </summary> /// <param name="foldername">指定文件夹名称,绝对路径</param> /// <param name="filefilter">文件类型过滤,根据文件后缀名,如:*,*.txt,*.xls</param> /// <param name="iscontainsubfolder">是否包含子文件夹</param> /// <returns>arraylist数组,为所有需要的文件路径名称</returns> public static ArrayList getallfilesbyfolder(string foldername, string filefilter, bool iscontainsubfolder) { ArrayList resarray = new ArrayList(); string[] files = Directory.GetFiles(foldername, filefilter); for (int i = 0; i < files.Length; i++) { resarray.Add(files[i]); } if (iscontainsubfolder) { string[] folders = Directory.GetDirectories(foldername); for (int j = 0; j < folders.Length; j++) { //遍历所有文件夹 ArrayList temp = getallfilesbyfolder(folders[j], filefilter, iscontainsubfolder); resarray.AddRange(temp); } } return resarray; } #endregion #region 获取指定文件夹下所有的文件名称,不过滤文件类型 /// <summary> /// 获取指定文件夹下所有的文件名称,不过滤文件类型 /// </summary> /// <param name="foldername">指定文件夹名称,绝对路径</param> /// <param name="iscontainsubfolder">是否包含子文件夹</param> /// <returns>arraylist数组,为所有需要的文件路径名称</returns> public static ArrayList getallfilesbyfolder(string foldername, bool iscontainsubfolder) { return getallfilesbyfolder(foldername, "*", iscontainsubfolder); } #endregion #region 删除非空文件夹 /// <summary> /// 删除非空文件夹 /// </summary> /// <param name="path">要删除的文件夹目录</param> public void DeleteDirectory(string path) { DirectoryInfo dir = new DirectoryInfo(path); if (dir.Exists) { DirectoryInfo[] childs = dir.GetDirectories(); foreach (DirectoryInfo child in childs) { child.Delete(true); } dir.Delete(true); } } #endregion #region 文件存在的路径 /// <summary> /// 文件存在的路径 /// </summary> /// <param name="tmpFile">要删除文件名称</param> public static void DeleteFile(string tmpFile) { if (!File.Exists(tmpFile)) { return; } else { File.Delete(tmpFile); } } #endregion }
未完待续。。。。。。
以上是关于代码记录的主要内容,如果未能解决你的问题,请参考以下文章
错误记录Flutter 混合开发获取 BinaryMessenger 报错 ( FlutterActivityAndFragmentDelegate.getFlutterEngine() )(代码片段
[未解决问题记录]python asyncio+aiohttp出现Exception ignored:RuntimeError('Event loop is closed')(代码片段