using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Data; using System.IO; using System.Net; using System.Net.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Web; using SuperMap.RealEstate.CoreFrameWork; using SuperMap.RealEstate.CoreFrameWork.Dictionary.Interface; using SuperMap.RealEstate.CoreFrameWork.Dictionary.Business; using SuperMap.RealEstate.Enums; using SuperMap.RealEstate.ServiceModel; using SuperMap.RealEstate.Web.UI.WebControls; using Newtonsoft.Json.Linq; namespace HZQR.Common.Common { /// /// 通用帮助类 /// public class CommonHelper { #region 方法 -> 绑定下拉框枚举信息 /// /// 绑定下拉框枚举信息 /// /// 枚举名称 /// 下拉框控件 /// 禁用行值 /// 搜索内容 /// public static void BindingDropDownList(string fieldexplain_field, List items, string disabledValue, string obscureValue, Transaction _Transaction) { BindingDropDownList(fieldexplain_field, items, disabledValue, obscureValue, false, _Transaction); } /// /// 绑定下拉框枚举信息 /// /// 枚举名称 /// 下拉框控件 /// 去除绑定的枚举值 /// 搜索枚举名称 /// 是否仅绑定有效数据 /// /// 查询枚举值域长度为ValueLength的值域 public static void BindingDropDownList(string fieldexplain_field, List items, string disabledValue, string obscureValue, bool status, Transaction _Transaction, int? ValueLength = null) { DataTable _DataTable = GetBindingDataSource(fieldexplain_field, string.Empty, string.Empty, obscureValue, _Transaction, ValueLength); BindingDropDownList(_DataTable, "-1", items, disabledValue, 0, true, status); } /// /// 绑定下拉框枚举信息 /// /// 数据源 /// 父级id /// 下拉框控件 /// 去除绑定的枚举值 /// 下拉框显示等级 /// 是否允许选择枚举 /// 是否仅绑定有效数据 private static void BindingDropDownList(DataTable _DataTable, string pid, List items, string disabledValue, int level, bool disabled, bool status) { ListItemEx _ListItem; foreach (DataRow _Row in _DataTable.Select("FieldEnum_PID = " + pid)) { if (_Row["FieldEnum_PID"].ToString() != pid) { continue; } if (status && (_Row["FieldEnum_Status"].ToString() == "2")) { continue; } bool _disabled = disabled; _ListItem = new ListItemEx(); if (status) { _ListItem.Value = _Row["FieldEnum_Value"].ToString(); } else { _ListItem.Value = _Row["FieldEnum_ID"].ToString(); } _ListItem.Text = _Row["FieldEnum_Name"].ToString(); _ListItem.Level = level; if (_ListItem.Value == disabledValue) { _disabled = false; } if ((status) && (_Row["FieldEnum_Status"].ToString() != "1")) { _ListItem.Enabled = false; } else { if (!_disabled) { _ListItem.Enabled = false; } } items.Add(_ListItem); BindingDropDownList(_DataTable, _Row["FieldEnum_ID"].ToString(), items, disabledValue, level + 1, _disabled, status); } } #endregion #region 方法 -> 获取数据源 /// public static DataTable GetBindingDataSource(string fieldExplain_ID, string pid, Transaction _Transaction) { return GetBindingDataSource(fieldExplain_ID, pid, string.Empty, string.Empty, _Transaction); } /// public static DataTable GetBindingDataSource(string fieldexplain_field, string pid, string obscureName, string obscureValue, Transaction _Transaction, int? ValueLength = null) { string _SQLStr1 = @"Select * From T_FieldEnum A Where Exists (Select 1 From T_FieldExplain B Where A.FieldExplain_ID = B.FieldExplain_ID And B.FieldExplain_Field = '{0}') {1} {2} Order By FieldEnum_PID,FieldEnum_Index,FieldEnum_Value"; string _SQLStr2 = string.IsNullOrEmpty(pid) ? "" : " And FieldEnum_PID = " + pid; string _SQLStr3 = string.IsNullOrEmpty(obscureName) ? "" : " And FieldEnum_Name Like '" + obscureName + "'"; if (!string.IsNullOrEmpty(obscureValue)) { _SQLStr3 += " And FieldEnum_Value Like '" + obscureValue + "'"; } if (ValueLength != null) { _SQLStr3 += " AND LENGTH(FieldEnum_Value) = " + ValueLength; } return new FieldEnum(_Transaction).ExecuteDataTable(string.Format(_SQLStr1, fieldexplain_field, _SQLStr2, _SQLStr3)); } #endregion #region 方法 -> 获取处理时效 public static string GetSumTimes(TimeSpan span, string TitleName = "") { if (span.TotalHours < 1) { return TitleName + "小于1小时"; } else if (span.TotalHours < 24) { return TitleName + span.Hours + "时"; } else { return TitleName + span.Days + "天"; } } #endregion #region 方法 -> 根据等级增加空格 string getlevelText(int level) { string _str = ""; for (int i = 0; i < level; i++) { _str += "  "; } if (string.IsNullOrEmpty(_str)) { return ""; } else { return System.Web.HttpContext.Current.Server.HtmlDecode(_str); } } #endregion #region 方法 -> 返回字典内容-方法释义待编写 /// /// 返回字典内容 /// /// /// /// /// /// public static Dictionary> GetDictionary( Transaction transaction, string obscureValue, int? ValueLength, params string[] FieldExplain_Fields) { if (FieldExplain_Fields == null || FieldExplain_Fields.Length == 0) { return null; } CarcheDictionaryEx _CarcheDictionaryEx; Dictionary> _Dictionary = new Dictionary>(); List _SearchFieldCollection = new List(); foreach (string FieldExplain_Field in FieldExplain_Fields) { string _FieldExplain_Field = FieldExplain_Field.ToUpper(); if (!_Dictionary.ContainsKey(_FieldExplain_Field)) { if (ServiceCacheHelper.Read(_FieldExplain_Field, out _CarcheDictionaryEx)) { _Dictionary.Add(_FieldExplain_Field, new Dictionary(_CarcheDictionaryEx.Dictionary)); } else { _SearchFieldCollection.Add("'" + _FieldExplain_Field + "'"); } } } if (_SearchFieldCollection.Count == 0) { return _Dictionary; } if (!string.IsNullOrEmpty(obscureValue)) { obscureValue = " And B.FieldEnum_Value Like '" + obscureValue + "'"; } if (ValueLength != null) { obscureValue += " AND LENGTH(B.FieldEnum_Value) = " + ValueLength; } FieldExplain _FieldExplain = new FieldExplain(transaction); string fullSqlString = string.Format(@"select A.FieldExplain_Field,B.FieldEnum_Name,B.FieldEnum_Value,B.FieldEnum_Index from T_FieldExplain A,T_FieldEnum B where A.FieldExplain_ID = B.FieldExplain_ID and A.FieldExplain_Field in ({0}){1} order by FieldExplain_Field,FieldEnum_Index,FieldEnum_Value", string.Join(",", _SearchFieldCollection.ToArray()), obscureValue); //throw new Exception(fullSqlString); Dictionary> _SearchDictionary = new Dictionary>(); DataRowCollection _DataRowCollection = _FieldExplain.ExecuteDataTable(fullSqlString).Rows; foreach (DataRow _DataRow in _DataRowCollection) { string _Key = _DataRow[TableSchema_FieldExplain.FieldExplain_Field].ToString(); if (!_SearchDictionary.ContainsKey(_Key)) { _SearchDictionary.Add(_Key, new Dictionary()); } _SearchDictionary[_Key].Add(_DataRow[TableSchema_FieldEnum.FieldEnum_Value].ToString(), _DataRow[TableSchema_FieldEnum.FieldEnum_Name].ToString()); } foreach (KeyValuePair> item in _SearchDictionary) { _CarcheDictionaryEx = new CarcheDictionaryEx(); _CarcheDictionaryEx.Dictionary = new Dictionary(item.Value); ServiceCacheHelper.Insert(item.Key, _CarcheDictionaryEx); _Dictionary.Add(item.Key, new Dictionary(item.Value)); } return _Dictionary; } /// /// 返回字典内容 /// /// /// public static Dictionary> GetDictionaryByYesNo(params string[] FieldExplain_Fields) { Dictionary _KeyDictionary = new Dictionary(); _KeyDictionary.Add("1", "是"); _KeyDictionary.Add("0", "否"); Dictionary> _DictionaryEnumCollection = new Dictionary>(); foreach (string _FieldExplainName in FieldExplain_Fields) { _DictionaryEnumCollection.Add(_FieldExplainName, _KeyDictionary); } return _DictionaryEnumCollection; } /// /// 返回字典内容 /// /// /// /// public static Dictionary GetDictionaryKeyValue(Transaction transaction, string obscureValue, int? ValueLength, string FieldExplain_Fields) { return GetDictionary(transaction, obscureValue, ValueLength, FieldExplain_Fields)[FieldExplain_Fields.ToUpper()]; } /// /// 返回字典内容 /// /// /// /// /// public static Dictionary> GetDictionary(string FieldName, EnumState state = EnumState.All) { return EnumHelper.GetGridViewDictionary(FieldName, state); } #endregion #region 方法 -> post请求接口 /// /// post请求接口 /// /// URL后面的参数 /// public static string PostService(string BaseUrl, string parameters, string provinceCode, string ContentType = "application/json", int timeout = 0) { string reString = ""; try { //设置访问站点 //string _BaseUrl = "192.168.10.117:8080/tenant/store/add"; //设置访问路由 string RequestUrl = BaseUrl + parameters; //获取业主单位对应参数名 string tenantDB = ConfigurationManager.AppSettings["tenantDB_" + provinceCode] != null ? ConfigurationManager.AppSettings["tenantDB_" + provinceCode].ToString() : ""; reString = HttpUrlPost(parameters, RequestUrl, tenantDB, ContentType, timeout); } catch (Exception ex) { reString = "error:" + ex.Message; } return reString; } #endregion #region 方法 -> HTTP报文请求 /// /// HTTP报文请求 /// /// /// /// /// /// /// public static string HttpUrlPost(string postDataStr, string RequestUrl, string tenantDB = "", string ContentType = "application/json", int timeout = 0) { try { System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; CookieContainer cookieContainer = new CookieContainer(); byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postDataStr); // 设置提交的相关参数 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); HttpWebRequest request = WebRequest.Create(RequestUrl) as HttpWebRequest; if (timeout > 0) { request.Timeout = timeout * 1000; } if (!string.IsNullOrWhiteSpace(tenantDB)) { request.Headers.Add("tenantDB", tenantDB); } request.Method = "POST"; request.KeepAlive = false; request.ContentType = ContentType; request.CookieContainer = cookieContainer; request.ContentLength = postBytes.Length; using (System.IO.Stream reqStream = request.GetRequestStream()) { reqStream.Write(postBytes, 0, postBytes.Length); } using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { //在这里对接收到的页面内容进行处理 //直到request.GetResponse()程序才开始向目标网页发送post请求 System.IO.Stream responseStream = response.GetResponseStream(); System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8")); string val = reader.ReadToEnd(); return val; } } catch (Exception ex) { SuperMap.RealEstate.Utility.ErrorLogHelper.Write(ex, "Post请求", "Post请求:" + postDataStr + "," + RequestUrl); return ex.ToString(); } } public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; } #endregion #region 方法 -> 将时间显示为日期格式 /// /// 将时间显示为日期格式 /// /// 时间 /// 数据格式:0【长日期】,1【短日期】,默认为1 /// string格式 public static string ChangeTimeToDateString(DateTime? _DateTime, int DataFormat = 1) { string DateString = ""; if (_DateTime != null) { switch (DataFormat) { //长日期 case 0: DateString = _DateTime.Value.ToLongDateString(); break; //短日期 case 1: DateString = _DateTime.Value.ToShortDateString(); break; } } return DateString; } #endregion #region 方法 -> 往数据中心表更新当前总部数据版本号 /// /// 往数据中心表更新当前总部数据版本号 /// /// 表名:T_COMMODITY(商品表);T_SHOPMESSAGE(门店); /// T_SELLWORKER(工号);T_SALESPROMOTE(促销);T_AUDITTASKS(智能稽核) /// 数据版本:时间格式 2010-10-10 12:12:12 /// 服务区编号 /// 门店编号 /// 机器编号 /// 业态 /// public static bool SynchroDataVersion(string TableName, string DataVersion, string ServerpartCode, string ShopCode = "", string MachineCode = "", string BusinessType = "") { //数据版本号同步地址 string SynchroUrl = ConfigurationManager.AppSettings["SynchroUrl"]; return SynchroDataVersion(SynchroUrl, TableName, DataVersion, ServerpartCode, ShopCode, MachineCode, BusinessType, ""); } /// /// 往云端数据中心表更新当前总部数据版本号 /// /// 表名:T_COMMODITYUNIFIED(统一定价) /// 数据版本:时间格式 2010-10-10 12:12:12 /// 省份编码 /// 业态 /// public static bool SynchroUniformDataVersion(string TableName, string DataVersion, string ProvinceCode, string BusinessType) { //数据版本号同步地址 string SynchroUrl = ConfigurationManager.AppSettings["SynchroUrl"]; return SynchroDataVersion(SynchroUrl, TableName, DataVersion, "", "", "", BusinessType, ProvinceCode); } /// /// 往云端数据中心表更新当前总部数据版本号 /// /// 数据版本号同步地址 /// 表名:T_COMMODITYUNIFIED(统一定价);T_COMMODITY(商品表);T_SHOPMESSAGE(门店); /// T_SELLWORKER(工号);T_SALESPROMOTE(促销);T_AUDITTASKS(智能稽核) /// 数据版本:时间格式 2010-10-10 12:12:12 /// 服务区编号 /// 门店编号 /// 机器编号 /// 业态 /// 省份编码 /// public static bool SynchroDataVersion(string SynchroUrl, string TableName, string DataVersion, string ServerpartCode, string ShopCode, string MachineCode, string BusinessType, string ProvinceCode) { Hashtable hashtable = new Hashtable(); hashtable.Add("TableName", TableName); hashtable.Add("ProvinceCode", ProvinceCode); hashtable.Add("DataVersion", DataVersion); hashtable.Add("ServerpartCode", ServerpartCode); hashtable.Add("ShopCode", ShopCode); hashtable.Add("MachineCode", MachineCode); hashtable.Add("BusinessType", BusinessType); string resultStr = SoapWSHelper.QuerySoapWebServiceString(SynchroUrl, "SetNewDataVersion", hashtable); JObject _JObject = JObject.Parse(resultStr); if (_JObject["error"].ToString() == "1") { return true; } else { LogUtil.WriteLog($"[{ TableName }]数据版本同步异常:" + _JObject["msg"].ToString()); return false; } } /// /// 往云端数据中心表更新当前总部上传数据版本号 /// /// 上传数据json数组 /// 提交数据类型(EndAccount:日结,Inspections:稽核,Personsell:交班,CommoditySale:单品) /// public static bool SynchroUploadDataVersion(string JsonString, string PostDataType) { //数据版本号同步地址 string SynchroUrl = ConfigurationManager.AppSettings["SynchroUploadUrl"]; return SynchroUploadDataVersion(JsonString, PostDataType, SynchroUrl); } /// /// 往云端数据中心表更新当前总部上传数据版本号 /// /// 上传数据json数组 /// 提交数据类型(EndAccount:日结,Inspections:稽核,Personsell:交班,CommoditySale:单品) /// 数据同步地址 /// public static bool SynchroUploadDataVersion(string JsonString, string PostDataType, string SynchroUrl) { Hashtable hashtable = new Hashtable(); hashtable.Add("JsonString", JsonString); hashtable.Add("PostDataType", PostDataType); string resultStr = SoapWSHelper.QuerySoapWebServiceString(SynchroUrl, "PostNewDataVersion", hashtable); JObject _JObject = JObject.Parse(resultStr); if (_JObject["error"].ToString() == "1") { return true; } else { LogUtil.WriteLog($"[{ PostDataType }]数据版本同步异常:" + _JObject["msg"].ToString()); return false; } } #endregion #region 方法 -> 创建md5 16位大写加密 public static string CreateMD5(string text) { var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); //换成utf8后对于中文加密也适用 byte[] output = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(text)); string pass2md5 = BitConverter.ToString(output, 4, 8).Replace("-", ""); //pass2md5 = pass2md5.ToUpper(); return pass2md5; } /// /// 32位大写 /// /// /// public static string Create32MD5(string text) { var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); //换成utf8后对于中文加密也适用 byte[] output = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(text)); string pass2md5 = BitConverter.ToString(output).Replace("-", ""); //pass2md5 = pass2md5.ToUpper(); return pass2md5; } #endregion #region 方法 -> 调用WebAPI接口 /// /// 调用商品同步WebAPI接口,同步商品至合作商户平台 /// /// /// /// public static string PostCommodityToWebAPI(string CommodityJson, string ProvinceCode, string ServerpartID) { string WebAPIUrl = ConfigurationManager.AppSettings["WebAPIUrl"]; string PostStr = string.Format("/DataTransfer/SynchroCommodity?CommodityJson={0}&ProvinceCode={1}&ServerpartID={2}", CommodityJson, ProvinceCode, ServerpartID); string format = "application/json;charset=UTF-8"; ; return HttpUrlPost(PostStr, WebAPIUrl, format); } /// /// 调用商品同步WebAPI接口,同步商品至综管平台 /// /// /// /// public static string PostCommodityToWebAPIIMP(string ProvinceCode, string CommodityJson, string ServerpartID) { string WebAPIUrl = ConfigurationManager.AppSettings["WebAPIUrl"] + "_" + ProvinceCode; string PostStr = string.Format("/DataTransfer/SynchroCommodity?CommodityJson={0}&ServerpartID={1}&ProvinceCode={2}", CommodityJson, ServerpartID, ProvinceCode); string format = "application/json;charset=UTF-8"; ; return HttpUrlPost(PostStr, WebAPIUrl, format); } /// /// 调用下发数据的WebAPI接口,下发指令至收银系统 /// /// 服务区编码集合【格式:服务区编码(6位)+门店编码(6位),多个参数用英文,隔开】 /// 传输表枚举值 /// 0:门店信息,1:商品类型,2:商品自定义类,3:商品信息,4:收银员信息 /// 5:智能稽核,6:促销信息,7:移动支付配置,8:机器参数 /// /// 数据下发时间 public static string PostCommandToSocketService(string ServerpartShopCodeS, string TableName, string OperateTime) { return PostCommandToSocketService(ServerpartShopCodeS, TableName, OperateTime, ""); } /// /// 调用下发数据的WebAPI接口,下发指令至收银系统 /// /// 服务区编码集合【格式:服务区编码(6位)+门店编码(6位),多个参数用英文,隔开】 /// 传输表枚举值 /// 0:门店信息,1:商品类型,2:商品自定义类,3:商品信息,4:收银员信息 /// 5:智能稽核,6:促销信息,7:移动支付配置,8:机器参数 /// /// 数据下发时间 /// 数据传输内容 public static string PostCommandToSocketService(string ServerpartShopCodeS, string TableName, string OperateTime, string SocketContent) { LogUtil.WriteLog(null, "开始下发指令:服务区编码集合【" + ServerpartShopCodeS + "】,传输表枚举值【" + TableName + "】,数据下发时间【" + OperateTime + "】,数据传输内容【" + SocketContent + "】", DateTime.Now.ToString("yyyyMMdd") + "_Command"); string WebAPIUrl = ConfigurationManager.AppSettings["WebAPIUrl_Command"] + "/WebSocket/sendSocketMsg"; JObject keyValuePairs = new JObject(); keyValuePairs["ServerpartShopCodeS"] = ServerpartShopCodeS; keyValuePairs["TableName"] = TableName; keyValuePairs["OperateTime"] = OperateTime; keyValuePairs["SocketContent"] = SocketContent; string parameters = Newtonsoft.Json.JsonConvert.SerializeObject(keyValuePairs); string Result = HttpUrlPost(parameters, WebAPIUrl); LogUtil.WriteLog(null, "返回结果:" + Result, DateTime.Now.ToString("yyyyMMdd") + "_Command"); return Result; } #region 记录服务区门店商家数量 /// /// 记录服务区门店商家数量 /// /// 服务区内码 /// 统计日期 public static string RecordShopCount(string Serverpart_ID, string Statistics_Date) { string WebAPIUrl = ConfigurationManager.AppSettings["CommercialApi"]; string PostStr = string.Format("/BaseInfo/RecordShopCount?Serverpart_ID={0}&Statistics_Date={1}", Serverpart_ID, Statistics_Date); string format = "application/x-www-form-urlencoded"; string resultstr = HttpUrlPost(PostStr, WebAPIUrl + PostStr, format); return resultstr; } #endregion #endregion #region 方法 -> 对字符串进行SHA1加密 /// /// 对字符串进行SHA1加密 /// /// 需要加密的字符串 /// 密文 public static string SHA1_Encrypt(string Source_String) { byte[] StrRes = Encoding.Default.GetBytes(Source_String); HashAlgorithm iSHA = new SHA1CryptoServiceProvider(); StrRes = iSHA.ComputeHash(StrRes); StringBuilder EnText = new StringBuilder(); foreach (byte iByte in StrRes) { EnText.AppendFormat("{0:x2}", iByte); } return EnText.ToString().ToUpper(); } #endregion #region 方法 -> 发送Post请求的方法 /// /// 发送POST请求方法 /// /// 目标URL地址 /// 以键值对的形式存储被Post传输的参数 /// public static string SendPost(string URL, NameValueCollection NVS) { using (var client = new WebClient()) { var response = client.UploadValues(URL, NVS); return Encoding.UTF8.GetString(response); } } #endregion #region 方法 -> 将字符串转换成UTF-8 /// /// 将字符串转换成UTF-8 /// /// 字符串 /// public static string get_uft8(string unicodeString) { UTF8Encoding utf8 = new UTF8Encoding(); //通过utf-8编码,将字符串转byte byte[] encodedBytes = utf8.GetBytes(unicodeString); //通过utf-8编码,将byte转字符串 string decodedString = utf8.GetString(encodedBytes); return decodedString; } #endregion #region 方法 -> 安徽航信开票二维码信息生成 /// /// 安徽航信开票二维码信息生成 /// /// 销方税号 /// 交易订单号 /// 交易时间 /// 订单金额 /// 服务区编码 /// 开票内容 /// 发票备注 /// 加密密钥 /// public static string CreateInvoiceInfo(string taxNumber, string orderCode, DateTime orderDate, decimal orderAmount, string serverpartCode, string goodsName, string invoiceDesc, string desKey) { //拼接开票二维码中content参数的明文字符串 //格式:销方税号;订单号;订单日期;服务区编号;商品名称,数量,含税金额*商品名称,数量,含税金额;备注 string sdtr_InvoiceInfo = taxNumber + ";" + orderCode + ";" + orderDate.ToString("yyyyMMddHHmmss") + ";" + serverpartCode + ";" + goodsName + "," + "," + orderAmount.ToString("F2") + ";" + invoiceDesc; //使用3DES对字符串进行加密并替换特殊字符后返回 return Encrypt3Des(sdtr_InvoiceInfo, desKey).Replace("/", "_a").Replace("+", "_b").Replace("=", "_c"); } #endregion #region 方法 -> 3des加密 ecb模式加密 /// /// 3des ecb模式加密 /// /// 待加密的字符串 /// 密钥 /// 运算模式 /// 加密矢量:只有在CBC解密模式下才适用 /// 加密后的字符串 public static string Encrypt3Des(string aStrString, string aStrKey, CipherMode mode = CipherMode.ECB, string iv = "12345678") { try { var des = new TripleDESCryptoServiceProvider { Key = Encoding.UTF8.GetBytes(aStrKey), Mode = mode }; if (mode == CipherMode.CBC) { des.IV = Encoding.UTF8.GetBytes(iv); } var desEncrypt = des.CreateEncryptor(); byte[] buffer = Encoding.UTF8.GetBytes(aStrString); return Convert.ToBase64String(desEncrypt.TransformFinalBlock(buffer, 0, buffer.Length)); } catch { return string.Empty; } } #endregion #region 方法 -> 上传文件至指定服务器 /// /// 上传文件至指定服务器 /// /// 文件夹路径 /// 文件名称 /// 文件类型 /// 二进制文件流 /// 传输地址,如http://10.104.1.8:8010/publish/FileUpload.ashx /// public static string PostFileToServer(string fileDir, string filename, string fileType, byte[] data, string postUrl) { string resultStr = ""; HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(postUrl); myRequest.Method = "POST"; myRequest.ContentType = fileType; myRequest.ContentLength = data.Length; myRequest.Headers.Add("FileName", HttpContext.Current.Server.UrlEncode(filename)); myRequest.Headers.Add("FileDir", HttpContext.Current.Server.UrlEncode(fileDir)); myRequest.Headers.Add("FileSize", data.Length.ToString()); //发送请求 using (Stream newStream = myRequest.GetRequestStream()) { newStream.Write(data, 0, data.Length); newStream.Close(); } //获取请求结果 using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse()) { StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); resultStr = reader.ReadToEnd(); reader.Close(); myResponse.Close(); } return resultStr; } #endregion #region 方法 -> 删除指定服务器的文件 /// /// 删除指定服务器的文件 /// /// 文件夹路径 /// 文件名称 /// 传输地址,如http://10.104.1.8:8010/publish/FileUpload.ashx /// public static string DelFileFromServer(string fileDir, string filename, string postUrl) { string resultStr = ""; HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(postUrl); myRequest.Method = "POST"; myRequest.Headers.Add("FileName", HttpContext.Current.Server.UrlEncode(filename)); myRequest.Headers.Add("FileDir", HttpContext.Current.Server.UrlEncode(fileDir)); myRequest.Headers.Add("FileDelete", "1"); byte[] data = new byte[0]; //发送请求 using (Stream newStream = myRequest.GetRequestStream()) { newStream.Write(data, 0, 0); newStream.Close(); } //获取请求结果 using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse()) { StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); resultStr = reader.ReadToEnd(); reader.Close(); myResponse.Close(); } return resultStr; } #endregion } }