chore: initial commit
This commit is contained in:
46
Interface_WebAPI/SlMesDbIterface/MessageHanlder/ApiTools.cs
Normal file
46
Interface_WebAPI/SlMesDbIterface/MessageHanlder/ApiTools.cs
Normal file
@@ -0,0 +1,46 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web.Http;
|
||||
using System.Net.Http;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace WebApi
|
||||
{
|
||||
public enum ResponseCode
|
||||
{
|
||||
Fail = 00000,
|
||||
Success = 00200,
|
||||
}
|
||||
|
||||
public class ApiTools
|
||||
{
|
||||
private string msgModel = "{{\"code\":{0},\"message\":\"{1}\",\"result\":{2}}}";
|
||||
public ApiTools()
|
||||
{
|
||||
}
|
||||
public HttpResponseMessage MsgFormat(ResponseCode code, string explanation, string result)
|
||||
{
|
||||
string r = @"^(\-|\+)?\d+(\.\d+)?$";
|
||||
string json = string.Empty;
|
||||
if (Regex.IsMatch(result, r) || result.ToLower() == "true" || result.ToLower() == "false" || result == "[]" || result.Contains('{'))
|
||||
{
|
||||
json = string.Format(msgModel, (int)code, explanation, result);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (result.Contains('"'))
|
||||
{
|
||||
json = string.Format(msgModel, (int)code, explanation, result);
|
||||
}
|
||||
else
|
||||
{
|
||||
json = string.Format(msgModel, (int)code, explanation, "\"" + result + "\"");
|
||||
}
|
||||
}
|
||||
return new HttpResponseMessage { Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") };
|
||||
}
|
||||
}
|
||||
}
|
||||
355
Interface_WebAPI/SlMesDbIterface/MessageHanlder/CallWebApi.cs
Normal file
355
Interface_WebAPI/SlMesDbIterface/MessageHanlder/CallWebApi.cs
Normal file
@@ -0,0 +1,355 @@
|
||||
using ExternalDataSync;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Configuration;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WebApi
|
||||
{
|
||||
public class Post
|
||||
{
|
||||
public static string Postring(string url, Dictionary<string, string> dic)
|
||||
{
|
||||
string result = "";
|
||||
//url = "http://172.16.22.15:8000/" + url;
|
||||
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
|
||||
req.Method = "POST";
|
||||
req.ContentType = "application/x-www-form-urlencoded";
|
||||
req.Proxy = null;
|
||||
|
||||
req.KeepAlive = false;
|
||||
|
||||
#region 添加Post 参数
|
||||
StringBuilder builder = new StringBuilder();
|
||||
int i = 0;
|
||||
foreach (var item in dic)
|
||||
{
|
||||
if (i > 0)
|
||||
builder.Append("&");
|
||||
builder.AppendFormat("{0}={1}", item.Key, item.Value);
|
||||
i++;
|
||||
}
|
||||
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
|
||||
req.ContentLength = data.Length;
|
||||
using (Stream reqStream = req.GetRequestStream())
|
||||
{
|
||||
reqStream.Write(data, 0, data.Length);
|
||||
reqStream.Close();
|
||||
}
|
||||
#endregion
|
||||
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
|
||||
Stream stream = resp.GetResponseStream();
|
||||
|
||||
//获取响应内容
|
||||
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
|
||||
{
|
||||
result = reader.ReadToEnd();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
public static string Post_XK(string url, string content)
|
||||
{
|
||||
|
||||
var WebapiPostHeader_Tenant = ConfigurationManager.AppSettings["WebapiPostHeader_Tenant"];
|
||||
var WebapiPostHeader_Language = ConfigurationManager.AppSettings["WebapiPostHeader_Language"];
|
||||
var WebapiPostHeader_Authorization = ConfigurationManager.AppSettings["WebapiPostHeader_Authorization"];
|
||||
var WebapiPostHeader_Systemcode = ConfigurationManager.AppSettings["WebapiPostHeader_Systemcode"];
|
||||
|
||||
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
|
||||
|
||||
string result = "";
|
||||
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
|
||||
|
||||
req.Headers.Add("X-ECC-Current-Tenant", WebapiPostHeader_Tenant);
|
||||
req.Headers.Add("Accept-Language", WebapiPostHeader_Language);
|
||||
req.Headers.Add("Authorization", WebapiPostHeader_Authorization);
|
||||
//req.Headers.Add("Connect-Type", "application/json");
|
||||
req.Headers.Add("Systemcode", WebapiPostHeader_Systemcode);
|
||||
|
||||
req.Accept = "*/*";
|
||||
req.Method = "POST";
|
||||
req.ContentType = "application/json";
|
||||
req.Timeout = 10000;
|
||||
|
||||
try
|
||||
{
|
||||
byte[] data = Encoding.UTF8.GetBytes(content);
|
||||
req.ContentLength = data.Length;
|
||||
using (Stream reqStream = req.GetRequestStream())
|
||||
{
|
||||
reqStream.Write(data, 0, data.Length);
|
||||
reqStream.Close();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return JsonConvert.SerializeObject(new { code = 500, message = ex.Message, data = new object() });
|
||||
}
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
|
||||
using (Stream stream = resp.GetResponseStream())
|
||||
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
|
||||
{
|
||||
result = reader.ReadToEnd();
|
||||
}
|
||||
}
|
||||
catch (WebException ex)
|
||||
{
|
||||
if (ex.Response != null)
|
||||
{
|
||||
using (Stream stream = ex.Response.GetResponseStream())
|
||||
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
|
||||
{
|
||||
result = reader.ReadToEnd();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
result = JsonConvert.SerializeObject(new { code = 500, message = ex.Message, data = new object() });
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
result = JsonConvert.SerializeObject(new { code = 500, message = ex.Message, data = new object() });
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static string Post_Auto(string url, string content)
|
||||
{
|
||||
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
|
||||
|
||||
string result = "";
|
||||
|
||||
try
|
||||
{
|
||||
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
|
||||
req.Headers.Add("Connect-Type", "application/json");
|
||||
req.Accept = "*/*";
|
||||
req.Method = "POST";
|
||||
req.ContentType = "application/json";
|
||||
req.Timeout = 10000;
|
||||
|
||||
// 写入请求数据
|
||||
if (!string.IsNullOrEmpty(content))
|
||||
{
|
||||
byte[] data = Encoding.UTF8.GetBytes(content);
|
||||
req.ContentLength = data.Length;
|
||||
using (Stream reqStream = req.GetRequestStream())
|
||||
{
|
||||
reqStream.Write(data, 0, data.Length);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
req.ContentLength = 0;
|
||||
}
|
||||
|
||||
// 获取响应
|
||||
using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
|
||||
using (Stream stream = resp.GetResponseStream())
|
||||
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
|
||||
{
|
||||
result = reader.ReadToEnd();
|
||||
}
|
||||
}
|
||||
catch (WebException ex)
|
||||
{
|
||||
if (ex.Response != null)
|
||||
{
|
||||
using (Stream stream = ex.Response.GetResponseStream())
|
||||
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
|
||||
{
|
||||
result = reader.ReadToEnd();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// 返回标准格式的错误信息
|
||||
result = JsonConvert.SerializeObject(new { code = 500, message = ex.Message });
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 返回标准格式的错误信息
|
||||
result = JsonConvert.SerializeObject(new { code = 500, message = ex.Message });
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static JObject Post_WebAPI(string WebAPI_Url, string m_msg)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonConvert.DeserializeObject<JObject>(WebApi.Post.Post_Auto(WebAPI_Url, m_msg));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new JObject { { "code", 500 }, { "Message", ex.Message }, { "data", new JObject() } };
|
||||
}
|
||||
}
|
||||
|
||||
public static string Postring1(string url, string token, Dictionary<string, string> dic)
|
||||
{
|
||||
string results = "";
|
||||
//url = "http://172.16.22.15:8000/" + url;
|
||||
|
||||
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
|
||||
req.Method = "POST";
|
||||
req.ContentType = "application/x-www-form-urlencoded";
|
||||
req.Headers.Add("Authorization", "Bearer " + token);
|
||||
|
||||
StringBuilder builder = new StringBuilder();
|
||||
int i = 0;
|
||||
foreach (var item in dic)
|
||||
{
|
||||
if (i > 0)
|
||||
builder.Append("&");
|
||||
builder.AppendFormat("{0}={1}", item.Key, item.Value);
|
||||
i++;
|
||||
}
|
||||
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
|
||||
req.ContentLength = data.Length;
|
||||
try
|
||||
{
|
||||
using (Stream reqStream = req.GetRequestStream())
|
||||
{
|
||||
reqStream.Write(data, 0, data.Length);
|
||||
reqStream.Close();
|
||||
}
|
||||
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
|
||||
Stream stream = resp.GetResponseStream();
|
||||
//获取响应内容
|
||||
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
|
||||
{
|
||||
results = reader.ReadToEnd();
|
||||
}
|
||||
return results;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine(e.Message);
|
||||
return e.Message;
|
||||
throw;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static string MyPost()
|
||||
{
|
||||
// var url = "http://192.168.1.224:41190/";
|
||||
var url = "http://127.0.0.1:41190/";
|
||||
var controller = "ZSaveTag";
|
||||
var action = "SelectPage";
|
||||
Dictionary<string, string> dict = new Dictionary<string, string>();
|
||||
dict.Add("OpName","");
|
||||
dict.Add("StartTime", "2022-06-24 00:00:00");
|
||||
dict.Add("EndTime", "2022-06-30 00:00:00");
|
||||
dict.Add("PageCurrent", "1");
|
||||
dict.Add("PageSize", "2");
|
||||
|
||||
|
||||
var reqUrl = url + "/api/" + controller + "/" + action;
|
||||
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(reqUrl);
|
||||
req.Method = "POST";
|
||||
req.ContentType = "application/json";
|
||||
req.Proxy = null;
|
||||
|
||||
req.KeepAlive = false;
|
||||
|
||||
#region 添加Post 参数
|
||||
JObject jObject = new JObject();
|
||||
jObject.Add("OpName", "");
|
||||
jObject.Add("StartTime", "2022-06-24 00:00:00");
|
||||
jObject.Add("EndTime", "2022-06-30 00:00:00");
|
||||
jObject.Add("PageCurrent", "2");
|
||||
jObject.Add("PageSize", "3");
|
||||
var jStr = jObject.ToString();
|
||||
|
||||
//StringBuilder builder = new StringBuilder();
|
||||
//int i = 0;
|
||||
//foreach (var item in dict)
|
||||
//{
|
||||
// if (i > 0)
|
||||
// builder.Append("&");
|
||||
// builder.AppendFormat("{0}={1}", item.Key, item.Value);
|
||||
// i++;
|
||||
//}
|
||||
//byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
|
||||
byte[] data = Encoding.UTF8.GetBytes(jStr);
|
||||
req.ContentLength = data.Length;
|
||||
using (Stream reqStream = req.GetRequestStream())
|
||||
{
|
||||
reqStream.Write(data, 0, data.Length);
|
||||
reqStream.Close();
|
||||
}
|
||||
#endregion
|
||||
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
|
||||
Stream stream = resp.GetResponseStream();
|
||||
|
||||
string result = "";
|
||||
|
||||
//获取响应内容
|
||||
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
|
||||
{
|
||||
result = reader.ReadToEnd();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static string MyPost(string url,string jsonStr)
|
||||
{
|
||||
string result = "";
|
||||
|
||||
try
|
||||
{
|
||||
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
|
||||
req.Method = "POST";
|
||||
req.ContentType = "application/json";
|
||||
req.Proxy = null;
|
||||
req.KeepAlive = false;
|
||||
|
||||
byte[] data = Encoding.UTF8.GetBytes(jsonStr);
|
||||
req.ContentLength = data.Length;
|
||||
using (Stream reqStream = req.GetRequestStream())
|
||||
{
|
||||
reqStream.Write(data, 0, data.Length);
|
||||
reqStream.Close();
|
||||
}
|
||||
|
||||
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
|
||||
Stream stream = resp.GetResponseStream();
|
||||
|
||||
|
||||
//获取响应内容
|
||||
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
|
||||
{
|
||||
result = reader.ReadToEnd();
|
||||
}
|
||||
Console.WriteLine(result);
|
||||
|
||||
|
||||
}
|
||||
catch (Exception err)
|
||||
{
|
||||
Console.WriteLine("<Error> " + err.Message);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
313
Interface_WebAPI/SlMesDbIterface/MessageHanlder/DeviceTools.cs
Normal file
313
Interface_WebAPI/SlMesDbIterface/MessageHanlder/DeviceTools.cs
Normal file
@@ -0,0 +1,313 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using TECSharpFunction;
|
||||
|
||||
namespace SlMesDbIterface
|
||||
{
|
||||
public class DeviceTools
|
||||
{
|
||||
public static void GetToolExcel(string FtpServer, string FtpUser,string FtpPassWord, string FtpFileList)
|
||||
{
|
||||
FTPHelper ftpClient = new FTPHelper(FtpServer, @"", FtpUser, FtpPassWord);
|
||||
//ListType=1代表获取文件列表,ListType=2代表获取文件夹列表,ListType=3代表获取文件和文件夹列表。
|
||||
//Detail=true时获文件或文件夹详细信息,Detail=false时只获取文件或文件夹名称。
|
||||
//Keyword是只需list名称包含Keyword的文件或文件夹,若要list所有文件或文件夹,则该参数为空。若ListType=3,则该参数无效。
|
||||
|
||||
int ListType = 1;
|
||||
bool Detail = false;
|
||||
string Keyword = "";
|
||||
|
||||
var fileList = ftpClient.GetFileDirctoryList(ListType, Detail, Keyword);
|
||||
|
||||
foreach (string itemFileName in fileList)
|
||||
{
|
||||
string tableName = itemFileName.Substring(0, itemFileName.LastIndexOf("."));
|
||||
if (FtpFileList.Contains(itemFileName))
|
||||
{
|
||||
ftpClient.Download(itemFileName, itemFileName, null);
|
||||
ExcelToDataTable(itemFileName, tableName);
|
||||
}
|
||||
else
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ExcelToDataTable(string excelPath, string tableName)
|
||||
{
|
||||
////判断是否包含当前日期的记录
|
||||
//int excelSheetindex = 0;
|
||||
//var dt = NPOITest.ExeclHelper.ExcelToDataTable(excelPath, excelSheetindex, true);
|
||||
//switch (tableName)
|
||||
//{
|
||||
// case "刀具柜-库存明细":
|
||||
// {
|
||||
// string str1 = "delete from[刀具柜-库存明细] where[导入日期] = '" + DateTime.Now.ToShortDateString() + "'";
|
||||
// DataLinkMesWork.SQLCommon.ExecuteSql(str1, Program.ConnectionString_MES, out string errorMessage1);
|
||||
// var dt_DB = GetToolDetail(dt);
|
||||
// SqlBulkCopyByDatatable(Program.ConnectionString_MES, tableName, dt_DB);
|
||||
// }
|
||||
// break;
|
||||
// case "刀具领用记录":
|
||||
// {
|
||||
// string str2 = "delete from[刀具领用记录] where[导入日期] = '" + DateTime.Now.ToShortDateString() + "'";
|
||||
// DataLinkMesWork.SQLCommon.ExecuteSql(str2, Program.ConnectionString_MES, out string errorMessage2);
|
||||
// var dt_DB = GetToolRecoder(dt);
|
||||
// SqlBulkCopyByDatatable(Program.ConnectionString_MES, tableName, dt_DB);
|
||||
// }
|
||||
// break;
|
||||
//}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 刀具领用记录
|
||||
/// </summary>
|
||||
private static DataTable GetToolRecoder(DataTable dtData)
|
||||
{
|
||||
//刀具领用记录.xls
|
||||
|
||||
DataTable dt = new DataTable();
|
||||
dt.Columns.Add("物料名称", typeof(System.String));
|
||||
dt.Columns.Add("物料编号", typeof(System.String));
|
||||
dt.Columns.Add("物料型号", typeof(System.String));
|
||||
dt.Columns.Add("供应商", typeof(System.String));//品牌(供应商)
|
||||
dt.Columns.Add("领取来源", typeof(System.String));
|
||||
dt.Columns.Add("领取数量", typeof(System.Int32));
|
||||
dt.Columns.Add("实领数量", typeof(System.Int32));
|
||||
dt.Columns.Add("领取单位", typeof(System.String));
|
||||
dt.Columns.Add("包装数量", typeof(System.Int32));
|
||||
dt.Columns.Add("包装单位", typeof(System.String));
|
||||
dt.Columns.Add("领用类型", typeof(System.String));
|
||||
dt.Columns.Add("单价", typeof(System.Double));//单价(元)
|
||||
dt.Columns.Add("金额", typeof(System.Double));
|
||||
dt.Columns.Add("部门", typeof(System.String));
|
||||
dt.Columns.Add("领用人员", typeof(System.String));
|
||||
dt.Columns.Add("已归还数量", typeof(System.Int32));
|
||||
dt.Columns.Add("是否归还", typeof(System.String));
|
||||
dt.Columns.Add("领用时间", typeof(System.DateTime));
|
||||
DataRow dr = dt.NewRow();
|
||||
for (int i = 0; i < dtData.Rows.Count; i++)
|
||||
{
|
||||
dr = dt.NewRow();
|
||||
var 物料名称 = dtData.Rows[i][0].ToString();
|
||||
if (物料名称 == "合计")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
dr["物料名称"] = 物料名称;
|
||||
dr["物料编号"] = dtData.Rows[i][1].ToString();
|
||||
dr["物料型号"] = dtData.Rows[i][2].ToString();
|
||||
dr["供应商"] = dtData.Rows[i][3].ToString();
|
||||
dr["领取来源"] = dtData.Rows[i][4].ToString();
|
||||
try
|
||||
{
|
||||
dr["领取数量"] = Convert.ToInt32(dtData.Rows[i][5]);
|
||||
}
|
||||
catch
|
||||
{
|
||||
dr["领取数量"] = 0;
|
||||
}
|
||||
try
|
||||
{
|
||||
dr["实领数量"] = Convert.ToInt32(dtData.Rows[i][6]);
|
||||
}
|
||||
catch
|
||||
{
|
||||
dr["实领数量"] = 0;
|
||||
}
|
||||
dr["领取单位"] = dtData.Rows[i][7].ToString();
|
||||
try
|
||||
{
|
||||
dr["包装数量"] = Convert.ToInt32(dtData.Rows[i][8]);
|
||||
}
|
||||
catch
|
||||
{
|
||||
dr["包装数量"] = 0;
|
||||
}
|
||||
|
||||
|
||||
dr["包装单位"] = dtData.Rows[i][9].ToString();
|
||||
dr["领用类型"] = dtData.Rows[i][10].ToString();
|
||||
try
|
||||
{
|
||||
dr["单价"] = Convert.ToDouble(dtData.Rows[i][11]);
|
||||
}
|
||||
catch
|
||||
{
|
||||
dr["单价"] = 0;
|
||||
}
|
||||
try
|
||||
{
|
||||
dr["金额"] = Convert.ToDouble(dtData.Rows[i][12]);
|
||||
}
|
||||
catch
|
||||
{
|
||||
dr["金额"] = 0;
|
||||
}
|
||||
dr["部门"] = dtData.Rows[i][13].ToString();
|
||||
dr["领用人员"] = dtData.Rows[i][14].ToString();
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
dr["已归还数量"] = Convert.ToInt32(dtData.Rows[i][15]);
|
||||
}
|
||||
catch
|
||||
{
|
||||
dr["已归还数量"] = 0;
|
||||
}
|
||||
dr["是否归还"] = dtData.Rows[i][16].ToString();
|
||||
try
|
||||
{
|
||||
dr["领用时间"] = Convert.ToDateTime(dtData.Rows[i][17]);
|
||||
// dr["领用时间"] = dtData.Rows[i][17].ToString();
|
||||
}
|
||||
catch
|
||||
{
|
||||
dr["领用时间"] = DBNull.Value;
|
||||
}
|
||||
|
||||
dt.Rows.Add(dr);
|
||||
}
|
||||
|
||||
|
||||
return dt;
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// 刀具柜-库存明细
|
||||
/// </summary>
|
||||
private static DataTable GetToolDetail(DataTable dtData)
|
||||
{
|
||||
//刀具柜 - 库存明细.xls
|
||||
|
||||
DataTable dt = new DataTable();
|
||||
dt.Columns.Add("刀具柜名称", typeof(System.String));
|
||||
dt.Columns.Add("行号", typeof(System.Int32));
|
||||
dt.Columns.Add("列号", typeof(System.Int32));
|
||||
dt.Columns.Add("物料名称", typeof(System.String));
|
||||
dt.Columns.Add("物料编号", typeof(System.String));
|
||||
dt.Columns.Add("物料型号", typeof(System.String));
|
||||
dt.Columns.Add("当前数量", typeof(System.Double));
|
||||
dt.Columns.Add("包装单位", typeof(System.String));
|
||||
dt.Columns.Add("单价", typeof(System.Double));
|
||||
dt.Columns.Add("金额", typeof(System.Double));
|
||||
dt.Columns.Add("最大存储", typeof(System.Int32));
|
||||
dt.Columns.Add("警告阀值", typeof(System.Int32));
|
||||
dt.Columns.Add("最后上架时间", typeof(System.DateTime));
|
||||
DataRow dr = dt.NewRow();
|
||||
for (int i = 0; i < dtData.Rows.Count; i++)
|
||||
{
|
||||
dr = dt.NewRow();
|
||||
dr["刀具柜名称"] = dtData.Rows[i]["刀具柜名称"].ToString();
|
||||
try
|
||||
{
|
||||
dr["行号"] = Convert.ToInt32(dtData.Rows[i]["行号"]);
|
||||
}
|
||||
catch
|
||||
{
|
||||
dr["行号"] = 0;
|
||||
}
|
||||
try
|
||||
{
|
||||
dr["列号"] = Convert.ToInt32(dtData.Rows[i]["列号"]);
|
||||
}
|
||||
catch
|
||||
{
|
||||
dr["列号"] = 0;
|
||||
}
|
||||
dr["物料名称"] = dtData.Rows[i]["物料名称"].ToString();
|
||||
dr["物料编号"] = dtData.Rows[i]["物料编号"].ToString();
|
||||
dr["物料型号"] = dtData.Rows[i]["物料型号"].ToString();
|
||||
try
|
||||
{
|
||||
dr["当前数量"] = Convert.ToDouble(dtData.Rows[i]["当前数量"]);
|
||||
}
|
||||
catch
|
||||
{
|
||||
dr["当前数量"] = 0;
|
||||
}
|
||||
dr["包装单位"] = dtData.Rows[i]["包装单位"].ToString();
|
||||
try
|
||||
{
|
||||
dr["单价"] = Convert.ToDouble(dtData.Rows[i]["单价"]);
|
||||
}
|
||||
catch
|
||||
{
|
||||
dr["单价"] = 0;
|
||||
}
|
||||
try
|
||||
{
|
||||
dr["金额"] = Convert.ToDouble(dtData.Rows[i]["金额"]);
|
||||
}
|
||||
catch
|
||||
{
|
||||
dr["金额"] = 0;
|
||||
}
|
||||
try
|
||||
{
|
||||
dr["最大存储"] = Convert.ToDouble(dtData.Rows[i]["最大存储"]);
|
||||
}
|
||||
catch
|
||||
{
|
||||
dr["最大存储"] = 0;
|
||||
}
|
||||
try
|
||||
{
|
||||
dr["警告阀值"] = Convert.ToDouble(dtData.Rows[i]["警告阀值"]);
|
||||
}
|
||||
catch
|
||||
{
|
||||
dr["警告阀值"] = 0;
|
||||
}
|
||||
try
|
||||
{
|
||||
dr["最后上架时间"] = Convert.ToDateTime(dtData.Rows[i]["最后上架时间"]);
|
||||
}
|
||||
catch
|
||||
{
|
||||
dr["警告阀值"] = DBNull.Value;
|
||||
}
|
||||
dt.Rows.Add(dr);
|
||||
}
|
||||
|
||||
|
||||
return dt;
|
||||
|
||||
}
|
||||
|
||||
static void SqlBulkCopyByDatatable(string connectionString, string TableName, DataTable dt)
|
||||
{
|
||||
using (SqlConnection conn = new SqlConnection(connectionString))
|
||||
{
|
||||
using (SqlBulkCopy sqlbulkcopy =
|
||||
new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction))
|
||||
{
|
||||
try
|
||||
{
|
||||
sqlbulkcopy.DestinationTableName = "[" + TableName + "]";
|
||||
dt.TableName = TableName;
|
||||
for (int i = 0; i < dt.Columns.Count; i++)
|
||||
{
|
||||
sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName.Trim(), "[" + dt.Columns[i].ColumnName + "]");
|
||||
}
|
||||
sqlbulkcopy.WriteToServer(dt);
|
||||
}
|
||||
catch (System.Exception ex)
|
||||
{
|
||||
//throw ex;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
332
Interface_WebAPI/SlMesDbIterface/MessageHanlder/FTPHelper.cs
Normal file
332
Interface_WebAPI/SlMesDbIterface/MessageHanlder/FTPHelper.cs
Normal file
@@ -0,0 +1,332 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Collections.Generic;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace TECSharpFunction
|
||||
{
|
||||
/// <summary>
|
||||
/// FTP操作
|
||||
/// </summary>
|
||||
public class FTPHelper
|
||||
{
|
||||
#region FTPConfig
|
||||
string ftpURI;
|
||||
string ftpUserID;
|
||||
string ftpServerIP;
|
||||
string ftpPassword;
|
||||
string ftpRemotePath;
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 连接FTP服务器
|
||||
/// </summary>
|
||||
/// <param name="FtpServerIP">FTP连接地址</param>
|
||||
/// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
|
||||
/// <param name="FtpUserID">用户名</param>
|
||||
/// <param name="FtpPassword">密码</param>
|
||||
public FTPHelper(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
|
||||
{
|
||||
ftpServerIP = FtpServerIP;
|
||||
ftpRemotePath = FtpRemotePath;
|
||||
ftpUserID = FtpUserID;
|
||||
ftpPassword = FtpPassword;
|
||||
ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
|
||||
}
|
||||
|
||||
public bool CheckFtp()
|
||||
{
|
||||
try
|
||||
{
|
||||
FtpWebRequest ftprequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
|
||||
// ftp用户名和密码
|
||||
ftprequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
|
||||
ftprequest.Method = WebRequestMethods.Ftp.ListDirectory;
|
||||
ftprequest.Timeout = 3000;
|
||||
FtpWebResponse ftpResponse = (FtpWebResponse)ftprequest.GetResponse();
|
||||
|
||||
ftpResponse.Close();
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// 参数localfile为要上传的本地文件,ftpfile为上传到FTP的文件名称,ProgressBar为显示上传进度的滚动条,适用于WinForm。若应用于控制台程序,只要重写该函数,将参数ProgressBar去掉即可,同时将函数实现里所有涉及ProgressBar的地方都删掉。
|
||||
//————————————————
|
||||
//版权声明:本文为CSDN博主「只会搬运的小菜鸟」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
|
||||
//原文链接:https://blog.csdn.net/u011465910/article/details/126563124
|
||||
public void Upload(string localfile, string ftpfile, System.Windows.Forms.ProgressBar pb)
|
||||
{
|
||||
FileInfo fileInf = new FileInfo(localfile);
|
||||
FtpWebRequest reqFTP;
|
||||
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfile));
|
||||
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
|
||||
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
|
||||
reqFTP.KeepAlive = false;
|
||||
reqFTP.UseBinary = true;
|
||||
reqFTP.ContentLength = fileInf.Length;
|
||||
if (pb != null)
|
||||
{
|
||||
pb.Maximum = Convert.ToInt32(reqFTP.ContentLength / 2048);
|
||||
pb.Maximum = pb.Maximum + 1;
|
||||
pb.Minimum = 0;
|
||||
pb.Value = 0;
|
||||
}
|
||||
int buffLength = 2048;
|
||||
byte[] buff = new byte[buffLength];
|
||||
int contentLen;
|
||||
FileStream fs = fileInf.OpenRead();
|
||||
try
|
||||
{
|
||||
Stream strm = reqFTP.GetRequestStream();
|
||||
contentLen = fs.Read(buff, 0, buffLength);
|
||||
while (contentLen != 0)
|
||||
{
|
||||
strm.Write(buff, 0, contentLen);
|
||||
if (pb != null)
|
||||
{
|
||||
if (pb.Value != pb.Maximum)
|
||||
pb.Value = pb.Value + 1;
|
||||
}
|
||||
contentLen = fs.Read(buff, 0, buffLength);
|
||||
System.Windows.Forms.Application.DoEvents();
|
||||
}
|
||||
if (pb != null)
|
||||
pb.Value = pb.Maximum;
|
||||
System.Windows.Forms.Application.DoEvents();
|
||||
strm.Close();
|
||||
fs.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception(ex.Message);
|
||||
}
|
||||
}
|
||||
//参数localfilename为将下载到本地的文件名称,ftpfilename为要下载的FTP上文件名称,
|
||||
// ProcessBar为用于显示下载进度的进度条。该函数用于WinForm,若用于控制台,只要重写该函数,删除所有涉及ProcessBar的代码即可。
|
||||
public void Download(string localfilename, string ftpfileName, System.Windows.Forms.ProgressBar pb)
|
||||
{
|
||||
long fileSize = GetFileSize(ftpfileName);
|
||||
if (fileSize > 0)
|
||||
{
|
||||
if (pb != null)
|
||||
{
|
||||
pb.Maximum = Convert.ToInt32(fileSize / 2048);
|
||||
pb.Maximum = pb.Maximum + 1;
|
||||
pb.Minimum = 0;
|
||||
pb.Value = 0;
|
||||
}
|
||||
try
|
||||
{
|
||||
FileStream outputStream = new FileStream(localfilename, FileMode.Create);
|
||||
FtpWebRequest reqFTP;
|
||||
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfileName));
|
||||
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
|
||||
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
|
||||
reqFTP.UseBinary = true;
|
||||
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
|
||||
Stream ftpStream = response.GetResponseStream();
|
||||
int bufferSize = 2048;
|
||||
|
||||
int readCount;
|
||||
byte[] buffer = new byte[bufferSize];
|
||||
readCount = ftpStream.Read(buffer, 0, bufferSize);
|
||||
while (readCount > 0)
|
||||
{
|
||||
outputStream.Write(buffer, 0, readCount);
|
||||
if (pb != null)
|
||||
{
|
||||
if (pb.Value != pb.Maximum)
|
||||
pb.Value = pb.Value + 1;
|
||||
}
|
||||
readCount = ftpStream.Read(buffer, 0, bufferSize);
|
||||
System.Windows.Forms.Application.DoEvents();
|
||||
}
|
||||
if (pb != null)
|
||||
pb.Value = pb.Maximum;
|
||||
System.Windows.Forms.Application.DoEvents();
|
||||
ftpStream.Close();
|
||||
outputStream.Close();
|
||||
response.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
File.Delete(localfilename);
|
||||
//throw new Exception(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Delete(string fileName)
|
||||
{
|
||||
try
|
||||
{
|
||||
FtpWebRequest reqFTP;
|
||||
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
|
||||
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
|
||||
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
|
||||
reqFTP.KeepAlive = false;
|
||||
string result = String.Empty;
|
||||
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
|
||||
long size = response.ContentLength;
|
||||
Stream datastream = response.GetResponseStream();
|
||||
StreamReader sr = new StreamReader(datastream);
|
||||
result = sr.ReadToEnd();
|
||||
sr.Close();
|
||||
datastream.Close();
|
||||
response.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception(ex.Message);
|
||||
}
|
||||
}
|
||||
//ListType=1代表获取文件列表,ListType=2代表获取文件夹列表,ListType=3代表获取文件和文件夹列表。
|
||||
//Detail=true时获文件或文件夹详细信息,Detail=false时只获取文件或文件夹名称。
|
||||
//Keyword是只需list名称包含Keyword的文件或文件夹,若要list所有文件或文件夹,则该参数为空。若ListType=3,则该参数无效。
|
||||
//————————————————
|
||||
//版权声明:本文为CSDN博主「只会搬运的小菜鸟」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
|
||||
public List<string> GetFileDirctoryList(int ListType, bool Detail, string Keyword)
|
||||
{
|
||||
List<string> strs = new List<string>();
|
||||
try
|
||||
{
|
||||
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
|
||||
// ftp用户名和密码
|
||||
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
|
||||
if (Detail)
|
||||
reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
|
||||
else
|
||||
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
|
||||
WebResponse response = reqFTP.GetResponse();
|
||||
|
||||
|
||||
StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名
|
||||
string line = reader.ReadLine();
|
||||
while (line != null)
|
||||
{
|
||||
if (ListType == 1)
|
||||
{
|
||||
if (line.Contains("."))
|
||||
{
|
||||
if (Keyword.Trim() == "*.*" || Keyword.Trim() == "")
|
||||
{
|
||||
strs.Add(line);
|
||||
}
|
||||
else if (line.IndexOf(Keyword.Trim()) > -1)
|
||||
{
|
||||
strs.Add(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (ListType == 2)
|
||||
{
|
||||
if (!line.Contains("."))
|
||||
{
|
||||
if (Keyword.Trim() == "*" || Keyword.Trim() == "")
|
||||
{
|
||||
strs.Add(line);
|
||||
}
|
||||
else if (line.IndexOf(Keyword.Trim()) > -1)
|
||||
{
|
||||
strs.Add(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (ListType == 3)
|
||||
{
|
||||
strs.Add(line);
|
||||
}
|
||||
line = reader.ReadLine();
|
||||
}
|
||||
reader.Close();
|
||||
response.Close();
|
||||
return strs;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception(ex.Message);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
public void MakeDir(string dirName)
|
||||
{
|
||||
FtpWebRequest reqFTP;
|
||||
try
|
||||
{
|
||||
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
|
||||
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
|
||||
reqFTP.UseBinary = true;
|
||||
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
|
||||
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
|
||||
Stream ftpStream = response.GetResponseStream();
|
||||
ftpStream.Close();
|
||||
response.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public long GetFileSize(string ftpfileName)
|
||||
{
|
||||
long fileSize = 0;
|
||||
try
|
||||
{
|
||||
FtpWebRequest reqFTP;
|
||||
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfileName));
|
||||
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
|
||||
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
|
||||
reqFTP.UseBinary = true;
|
||||
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
|
||||
Stream ftpStream = response.GetResponseStream();
|
||||
fileSize = response.ContentLength;
|
||||
ftpStream.Close();
|
||||
response.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception(ex.Message);
|
||||
}
|
||||
return fileSize;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public void ReName(string currentFilename, string newFilename)
|
||||
{
|
||||
FtpWebRequest reqFTP;
|
||||
try
|
||||
{
|
||||
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename));
|
||||
reqFTP.Method = WebRequestMethods.Ftp.Rename;
|
||||
reqFTP.RenameTo = newFilename;
|
||||
reqFTP.UseBinary = true;
|
||||
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
|
||||
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
|
||||
Stream ftpStream = response.GetResponseStream();
|
||||
ftpStream.Close();
|
||||
response.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public void MovieFile(string currentFilename, string newDirectory)
|
||||
{
|
||||
ReName(currentFilename, newDirectory);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
69
Interface_WebAPI/SlMesDbIterface/MessageHanlder/GetVal.cs
Normal file
69
Interface_WebAPI/SlMesDbIterface/MessageHanlder/GetVal.cs
Normal file
@@ -0,0 +1,69 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace RecData
|
||||
{
|
||||
public class GetVal
|
||||
{
|
||||
|
||||
public static string JObject_Value(JObject jObj,string name)
|
||||
{
|
||||
var objVal = "NULL";
|
||||
if (jObj[name] != null)
|
||||
{
|
||||
objVal = jObj[name].ToString();
|
||||
}
|
||||
return objVal;
|
||||
}
|
||||
public static string JObject_Value_Int(JObject jObj, string name)
|
||||
{
|
||||
var objVal = "-1";
|
||||
if (jObj[name] != null)
|
||||
{
|
||||
objVal = jObj[name].ToString();
|
||||
}
|
||||
return objVal;
|
||||
}
|
||||
public static string JToken_Value(JToken jToken, string name)
|
||||
{
|
||||
var objVal = "NULL";
|
||||
var jTokenStr = jToken.ToString();
|
||||
if (!jTokenStr.Contains(name))
|
||||
{
|
||||
return objVal;
|
||||
}
|
||||
|
||||
if (jToken[name] != null)
|
||||
{
|
||||
objVal = jToken[name].ToString();
|
||||
}
|
||||
return objVal;
|
||||
|
||||
}
|
||||
public static string JToken_Value_Int(JToken jToken, string name)
|
||||
{
|
||||
var objVal = "-1";
|
||||
if (jToken[name] != null)
|
||||
{
|
||||
objVal = jToken[name].ToString();
|
||||
}
|
||||
return objVal;
|
||||
|
||||
}
|
||||
public static JArray JObject_JArray(JObject jObj, string name)
|
||||
{
|
||||
var jArray = new JArray();
|
||||
if (jObj[name] != null)
|
||||
{
|
||||
jArray = (JArray)jObj[name];
|
||||
}
|
||||
return jArray;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
349
Interface_WebAPI/SlMesDbIterface/MessageHanlder/HttpCli.cs
Normal file
349
Interface_WebAPI/SlMesDbIterface/MessageHanlder/HttpCli.cs
Normal file
@@ -0,0 +1,349 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace PLMTEST
|
||||
{
|
||||
public class HttpCli
|
||||
{
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 指定Url地址使用Get 方式获取全部字符串
|
||||
/// </summary>
|
||||
/// <param name="url">请求链接地址</param>
|
||||
/// <returns></returns>
|
||||
public static string Get(string url)
|
||||
{
|
||||
string result = "";
|
||||
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
|
||||
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
|
||||
Stream stream = resp.GetResponseStream();
|
||||
try
|
||||
{
|
||||
//获取内容
|
||||
using (StreamReader reader = new StreamReader(stream))
|
||||
{
|
||||
result = reader.ReadToEnd();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
stream.Close();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void GetFile(string url,string path)
|
||||
{
|
||||
WebRequest request = WebRequest.Create(url);
|
||||
WebResponse response = request.GetResponse();
|
||||
if (response.ContentType.ToLower().Length > 0)
|
||||
{
|
||||
using (Stream reader = response.GetResponseStream())
|
||||
{
|
||||
using (FileStream writer = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
|
||||
{
|
||||
byte[] buffer = new byte[1024];
|
||||
int c = 0;
|
||||
while ((c = reader.Read(buffer, 0, buffer.Length)) > 0)
|
||||
{
|
||||
writer.Write(buffer, 0, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
//HttpContext
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] GetFile_Bytes(string url)
|
||||
{
|
||||
byte[] bytesAll = null;
|
||||
WebRequest request = WebRequest.Create(url);
|
||||
WebResponse response = request.GetResponse();
|
||||
if (response.ContentType.ToLower().Length > 0)
|
||||
{
|
||||
using (Stream reader = response.GetResponseStream())
|
||||
{
|
||||
MemoryStream ms = new MemoryStream();
|
||||
byte[] buffer = new byte[1024];
|
||||
while (true)
|
||||
{
|
||||
int sz = reader.Read(buffer, 0, 1024);
|
||||
if (sz == 0) break;
|
||||
ms.Write(buffer, 0, sz);
|
||||
}
|
||||
bytesAll = ms.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
//如是图片
|
||||
//System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
|
||||
|
||||
return bytesAll;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public void FGHJ()
|
||||
{
|
||||
|
||||
// Create a 'WebRequest' object with the specified url.
|
||||
WebRequest myWebRequest = WebRequest.Create("http://www.contoso.com");
|
||||
|
||||
// Send the 'WebRequest' and wait for response.
|
||||
WebResponse myWebResponse = myWebRequest.GetResponse();
|
||||
|
||||
// Obtain a 'Stream' object associated with the response object.
|
||||
Stream ReceiveStream = myWebResponse.GetResponseStream();
|
||||
|
||||
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
|
||||
|
||||
// Pipe the stream to a higher level stream reader with the required encoding format.
|
||||
StreamReader readStream = new StreamReader(ReceiveStream, encode);
|
||||
Console.WriteLine("\nResponse stream received");
|
||||
Char[] read = new Char[256];
|
||||
|
||||
// Read 256 charcters at a time.
|
||||
int count = readStream.Read(read, 0, 256);
|
||||
Console.WriteLine("HTML...\r\n");
|
||||
|
||||
while (count > 0)
|
||||
{
|
||||
// Dump the 256 characters on a string and display the string onto the console.
|
||||
String str = new String(read, 0, count);
|
||||
Console.Write(str);
|
||||
count = readStream.Read(read, 0, 256);
|
||||
}
|
||||
|
||||
Console.WriteLine("");
|
||||
// Release the resources of stream object.
|
||||
readStream.Close();
|
||||
|
||||
// Release the resources of response object.
|
||||
myWebResponse.Close();
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发送Get请求
|
||||
/// </summary>
|
||||
/// <param name="url">地址</param>
|
||||
/// <param name="dic">请求参数定义</param>
|
||||
/// <returns></returns>
|
||||
public static string Get(string url, Dictionary<string, string> dic)
|
||||
{
|
||||
string result = "";
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.Append(url);
|
||||
if (dic.Count > 0)
|
||||
{
|
||||
builder.Append("?");
|
||||
int i = 0;
|
||||
foreach (var item in dic)
|
||||
{
|
||||
if (i > 0)
|
||||
builder.Append("&");
|
||||
builder.AppendFormat("{0}={1}", item.Key, item.Value);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(builder.ToString());
|
||||
//添加参数
|
||||
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
|
||||
Stream stream = resp.GetResponseStream();
|
||||
try
|
||||
{
|
||||
//获取内容
|
||||
using (StreamReader reader = new StreamReader(stream))
|
||||
{
|
||||
result = reader.ReadToEnd();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
stream.Close();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 指定Post地址使用Get 方式获取全部字符串
|
||||
/// </summary>
|
||||
/// <param name="url">请求后台地址</param>
|
||||
/// <returns></returns>
|
||||
public static string Post(string url)
|
||||
{
|
||||
string result = "";
|
||||
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
|
||||
req.Method = "POST";
|
||||
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
|
||||
Stream stream = resp.GetResponseStream();
|
||||
//获取内容
|
||||
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
|
||||
{
|
||||
result = reader.ReadToEnd();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 指定Post地址使用Get 方式获取全部字符串
|
||||
/// </summary>
|
||||
/// <param name="url">请求后台地址</param>
|
||||
/// <returns></returns>
|
||||
public static string Post(string url, Dictionary<string, string> dic)
|
||||
{
|
||||
string result = "";
|
||||
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
|
||||
req.Method = "POST";
|
||||
req.ContentType = "application/x-www-form-urlencoded";
|
||||
#region 添加Post 参数
|
||||
StringBuilder builder = new StringBuilder();
|
||||
int i = 0;
|
||||
foreach (var item in dic)
|
||||
{
|
||||
if (i > 0)
|
||||
builder.Append("&");
|
||||
builder.AppendFormat("{0}={1}", item.Key, item.Value);
|
||||
i++;
|
||||
}
|
||||
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
|
||||
req.ContentLength = data.Length;
|
||||
using (Stream reqStream = req.GetRequestStream())
|
||||
{
|
||||
reqStream.Write(data, 0, data.Length);
|
||||
reqStream.Close();
|
||||
}
|
||||
#endregion
|
||||
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
|
||||
Stream stream = resp.GetResponseStream();
|
||||
//获取响应内容
|
||||
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
|
||||
{
|
||||
result = reader.ReadToEnd();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 指定Post地址使用Get 方式获取全部字符串
|
||||
/// </summary>
|
||||
/// <param name="url">请求后台地址</param>
|
||||
/// <param name="content">Post提交数据内容(utf-8编码的)</param>
|
||||
/// <returns></returns>
|
||||
public static string Post(string url, string content)
|
||||
{
|
||||
string result = "";
|
||||
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
|
||||
req.Method = "POST";
|
||||
req.ContentType = "application/json";
|
||||
|
||||
#region 添加Post 参数
|
||||
byte[] data = Encoding.UTF8.GetBytes(content);
|
||||
req.ContentLength = data.Length;
|
||||
using (Stream reqStream = req.GetRequestStream())
|
||||
{
|
||||
reqStream.Write(data, 0, data.Length);
|
||||
reqStream.Close();
|
||||
}
|
||||
#endregion
|
||||
|
||||
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
|
||||
Stream stream = resp.GetResponseStream();
|
||||
//获取响应内容
|
||||
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
|
||||
{
|
||||
result = reader.ReadToEnd();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Http下载文件
|
||||
/// </summary>
|
||||
/// <param name="uri">下载地址</param>
|
||||
/// <param name="filefullpath">存放完整路径(含文件名)</param>
|
||||
/// <param name="size">每次多的大小</param>
|
||||
/// <returns>下载操作是否成功</returns>
|
||||
|
||||
public static bool DownLoadFiles(string uri, string filefullpath, int size = 1000000)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(filefullpath))
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(filefullpath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
string fileDirectory = System.IO.Path.GetDirectoryName(filefullpath);
|
||||
|
||||
if (!Directory.Exists(fileDirectory))
|
||||
{
|
||||
Directory.CreateDirectory(fileDirectory);
|
||||
}
|
||||
|
||||
FileStream fs = new FileStream(filefullpath, FileMode.Create);
|
||||
|
||||
byte[] buffer = new byte[size];
|
||||
|
||||
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
|
||||
|
||||
request.Timeout = 100000;
|
||||
|
||||
request.AddRange((int)fs.Length);
|
||||
|
||||
Stream ns = request.GetResponse().GetResponseStream();
|
||||
|
||||
long contentLength = request.GetResponse().ContentLength;
|
||||
|
||||
int length = ns.Read(buffer, 0, buffer.Length);
|
||||
|
||||
while (length > 0)
|
||||
{
|
||||
fs.Write(buffer,0 , length);
|
||||
buffer = new byte[size];
|
||||
length = ns.Read(buffer, 0, buffer.Length);
|
||||
}
|
||||
|
||||
fs.Close();
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
150
Interface_WebAPI/SlMesDbIterface/MessageHanlder/InitServer.cs
Normal file
150
Interface_WebAPI/SlMesDbIterface/MessageHanlder/InitServer.cs
Normal file
@@ -0,0 +1,150 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Configuration;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Formatting;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Web.Http;
|
||||
using System.Web.Http.Cors;
|
||||
using System.Web.Http.SelfHost;
|
||||
|
||||
namespace WebApi
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class InitServer
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
HttpSelfHostConfiguration config = null;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
HttpSelfHostServer server = null;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="port"></param>
|
||||
public InitServer(int port)
|
||||
{
|
||||
config = new HttpSelfHostConfiguration($"http://0.0.0.0:{port}");
|
||||
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
|
||||
config.MapHttpAttributeRoutes();
|
||||
config.MaxReceivedMessageSize = 1024 * 1024 * 10;
|
||||
//config.Routes.MapHttpRoute(
|
||||
// name: "DefaultApi",
|
||||
// routeTemplate: "api/{controller}/{id}",
|
||||
// defaults: new { id = RouteParameter.Optional }
|
||||
//);
|
||||
|
||||
// 自定义路由匹配到action
|
||||
config.Routes.MapHttpRoute(
|
||||
name: "API Default",
|
||||
routeTemplate: "api/{controller}/{id}",
|
||||
defaults: new { id = RouteParameter.Optional }
|
||||
);
|
||||
|
||||
server = new HttpSelfHostServer(config);
|
||||
|
||||
server.OpenAsync().Wait();
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="port"></param>
|
||||
public void Init(int port)
|
||||
{
|
||||
|
||||
|
||||
}
|
||||
public void Close()
|
||||
{
|
||||
server.CloseAsync();
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class JsonContentNegotiator : IContentNegotiator
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
private readonly JsonMediaTypeFormatter _jsonFormatter;
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="formatter"></param>
|
||||
public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
|
||||
{
|
||||
_jsonFormatter = formatter;
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <param name="request"></param>
|
||||
/// <param name="formatters"></param>
|
||||
/// <returns></returns>
|
||||
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
|
||||
{
|
||||
var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
|
||||
return result;
|
||||
}
|
||||
|
||||
public static string Postring1(string url, string token, Dictionary<string, string> dic)
|
||||
{
|
||||
string results = "";
|
||||
//url = "http://172.16.22.15:8000/" + url;
|
||||
|
||||
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
|
||||
req.Method = "POST";
|
||||
req.ContentType = "application/x-www-form-urlencoded";
|
||||
req.Headers.Add("Authorization", "Bearer " + token);
|
||||
|
||||
StringBuilder builder = new StringBuilder();
|
||||
int i = 0;
|
||||
foreach (var item in dic)
|
||||
{
|
||||
if (i > 0)
|
||||
builder.Append("&");
|
||||
builder.AppendFormat("{0}={1}", item.Key, item.Value);
|
||||
i++;
|
||||
}
|
||||
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
|
||||
req.ContentLength = data.Length;
|
||||
try
|
||||
{
|
||||
using (Stream reqStream = req.GetRequestStream())
|
||||
{
|
||||
reqStream.Write(data, 0, data.Length);
|
||||
reqStream.Close();
|
||||
}
|
||||
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
|
||||
Stream stream = resp.GetResponseStream();
|
||||
//获取响应内容
|
||||
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
|
||||
{
|
||||
results = reader.ReadToEnd();
|
||||
}
|
||||
return results;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine(e.Message);
|
||||
return e.Message;
|
||||
throw;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
using ICSharpCode.SharpZipLib.Zip;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web.UI.WebControls;
|
||||
|
||||
namespace ExternalDataSync.MessageHanlder
|
||||
{
|
||||
public class LocalNetworkFileHelper
|
||||
{
|
||||
[DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
|
||||
public extern static bool PathFileExists(string path);
|
||||
/// <summary>
|
||||
/// 连接远程共享文件夹
|
||||
/// </summary>
|
||||
/// <param name="path">远程共享文件夹的路径</param>
|
||||
/// <param name="userName">用户名</param>
|
||||
/// <param name="passWord">密码</param>
|
||||
public static bool connectState(string path, string userName, string passWord, out string Sharefile_Error)
|
||||
{
|
||||
Sharefile_Error = "";
|
||||
bool Flag = false;
|
||||
Process proc = new Process();
|
||||
try
|
||||
{
|
||||
proc.StartInfo.FileName = "cmd.exe";
|
||||
proc.StartInfo.UseShellExecute = false;
|
||||
proc.StartInfo.RedirectStandardInput = true;
|
||||
proc.StartInfo.RedirectStandardOutput = true;
|
||||
proc.StartInfo.RedirectStandardError = true;
|
||||
proc.StartInfo.CreateNoWindow = true;
|
||||
proc.Start();
|
||||
string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
|
||||
proc.StandardInput.WriteLine(dosLine);
|
||||
proc.StandardInput.WriteLine("exit");
|
||||
while (!proc.HasExited)
|
||||
{
|
||||
proc.WaitForExit(1000);
|
||||
}
|
||||
string errormsg = proc.StandardError.ReadToEnd();
|
||||
proc.StandardError.Close();
|
||||
if (string.IsNullOrEmpty(errormsg))
|
||||
{
|
||||
Flag = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
Sharefile_Error = errormsg;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Sharefile_Error = ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
proc.Close();
|
||||
proc.Dispose();
|
||||
}
|
||||
return Flag;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从远程服务器下载文件到本地
|
||||
/// </summary>
|
||||
/// <param name="SourceFile">远程服务器路径(共享文件夹路径)</param>
|
||||
/// <param name="LocalFile">下载到本地后的文件路径</param>
|
||||
/// <param name="LocalFileName">下载到本地文件名称,包含扩展名:ABC.text</param>
|
||||
public static bool TransportRemoteToLocal(string SourceFile, string LocalFile, string LocalFileName, out string Sharefile_Error, out byte[] fileContent)
|
||||
{
|
||||
fileContent = null;
|
||||
Sharefile_Error = "";
|
||||
bool rel = false;
|
||||
try
|
||||
{
|
||||
|
||||
if (Directory.Exists(LocalFile))
|
||||
{
|
||||
Directory.Delete(LocalFile, true);
|
||||
}
|
||||
Directory.CreateDirectory(LocalFile);
|
||||
//从远程服务器下载到本地的文件
|
||||
if (LocalFile.EndsWith(@"\"))
|
||||
{
|
||||
LocalFile = LocalFile + LocalFileName;
|
||||
}
|
||||
else
|
||||
{
|
||||
LocalFile = LocalFile + "\\" + LocalFileName;
|
||||
}
|
||||
//远程服务器文件 此处假定远程服务器共享文件夹下确实包含本文件,否则程序报错
|
||||
FileStream inFileStream = new FileStream(SourceFile, FileMode.Open);
|
||||
FileStream outFileStream = new FileStream(LocalFile, FileMode.OpenOrCreate);
|
||||
byte[] buf = new byte[inFileStream.Length];
|
||||
int byteCount;
|
||||
while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
|
||||
{
|
||||
outFileStream.Write(buf, 0, byteCount);
|
||||
fileContent = new byte[buf.Length];
|
||||
Array.Copy(buf, fileContent, buf.Length);
|
||||
}
|
||||
inFileStream.Flush();
|
||||
inFileStream.Close();
|
||||
outFileStream.Flush();
|
||||
outFileStream.Close();
|
||||
rel = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Sharefile_Error = ex.Message;
|
||||
}
|
||||
return rel;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从远程服务器下载文件到本地
|
||||
/// </summary>
|
||||
/// <param name="SourceFile">远程服务器路径(共享文件夹路径)</param>
|
||||
/// <param name="LocalFile">下载到本地后的文件路径</param>
|
||||
public static bool TransportRemoteToLocal(string SourceFilePath, string LocalFilePath, out string Sharefile_Error)
|
||||
{
|
||||
Sharefile_Error = "";
|
||||
bool rel = false;
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(SourceFilePath))
|
||||
{
|
||||
Sharefile_Error = "共享文件路径不存在!" + SourceFilePath;
|
||||
return false;
|
||||
}
|
||||
if (!Directory.Exists(LocalFilePath))
|
||||
{
|
||||
Directory.CreateDirectory(LocalFilePath);
|
||||
}
|
||||
IEnumerable<string> files = System.IO.Directory.EnumerateFileSystemEntries(SourceFilePath);
|
||||
if (files != null && files.Count() > 0)
|
||||
{
|
||||
foreach (var item in files)
|
||||
{
|
||||
string desPath = System.IO.Path.Combine(LocalFilePath, System.IO.Path.GetFileName(item));
|
||||
//如果是文件
|
||||
var fileExist = System.IO.File.Exists(item);
|
||||
if (fileExist)
|
||||
{
|
||||
//复制文件到指定目录下
|
||||
System.IO.File.Copy(item, desPath, true);
|
||||
continue;
|
||||
}
|
||||
//如果是文件夹
|
||||
TransportRemoteToLocal(item, desPath, out string aaa);
|
||||
}
|
||||
}
|
||||
rel = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Sharefile_Error = ex.Message;
|
||||
}
|
||||
return rel;
|
||||
}
|
||||
public static class DirectoryExtension
|
||||
{
|
||||
public static bool IsShareAccessible(string path)
|
||||
{
|
||||
|
||||
return true;
|
||||
|
||||
//Ping ping = new Ping();
|
||||
//var response = ping.Send(path, 4);
|
||||
|
||||
|
||||
//string errorMessage;
|
||||
//var timeStart = DateTime.Now;
|
||||
//using (var process = new Process {
|
||||
// StartInfo = {
|
||||
// FileName = "cmd.exe",
|
||||
// UseShellExecute = false,
|
||||
// RedirectStandardInput = true,
|
||||
// RedirectStandardOutput = true,
|
||||
// CreateNoWindow = true,
|
||||
// RedirectStandardError = true
|
||||
// }
|
||||
//})
|
||||
//{
|
||||
// process.Start();
|
||||
// process.StandardInput.AutoFlush = true;
|
||||
// process.StandardInput.WriteLine(@"net use " + path);
|
||||
// process.StandardInput.WriteLine("exit");
|
||||
// errorMessage = process.StandardError.ReadToEnd();
|
||||
// process.WaitForExit();
|
||||
// if (string.IsNullOrEmpty(errorMessage))
|
||||
// {
|
||||
// return true;
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// return false;
|
||||
// }
|
||||
//}
|
||||
}
|
||||
|
||||
public static bool FtpFolderExists(string folderPath, string username, string password)
|
||||
{
|
||||
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(folderPath);
|
||||
request.Credentials = new NetworkCredential(username, password);
|
||||
request.Method = WebRequestMethods.Ftp.ListDirectory;
|
||||
|
||||
try
|
||||
{
|
||||
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
|
||||
{
|
||||
return true; // 如果成功获取响应,则文件夹存在
|
||||
}
|
||||
}
|
||||
catch (WebException ex)
|
||||
{
|
||||
return false; // 文件夹不存在
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// 从远程服务器下载文件到本地
|
||||
/// </summary>
|
||||
/// <param name="SourceFile">远程服务器路径(共享文件夹路径)</param>
|
||||
/// <param name="LocalFile">下载到本地后的文件路径</param>
|
||||
/// <param name="LocalFileName">下载到本地文件名称,包含扩展名:ABC.text</param>
|
||||
public static bool TransportRemoteToLocalZip(string SourceFile, string LocalFile, string LocalFileName, string zipedFolder, out string Sharefile_Error)
|
||||
{
|
||||
Sharefile_Error = "";
|
||||
bool rel = false;
|
||||
try
|
||||
{
|
||||
//远程服务器文件 此处假定远程服务器共享文件夹下确实包含本文件,否则程序报错
|
||||
FileStream inFileStream = new FileStream(SourceFile, FileMode.Open);
|
||||
if (Directory.Exists(LocalFile))
|
||||
{
|
||||
Directory.Delete(LocalFile, true);
|
||||
}
|
||||
Directory.CreateDirectory(LocalFile);
|
||||
//从远程服务器下载到本地的文件
|
||||
if (LocalFile.EndsWith(@"\"))
|
||||
{
|
||||
LocalFile = LocalFile + LocalFileName;
|
||||
}
|
||||
else
|
||||
{
|
||||
LocalFile = LocalFile + "\\" + LocalFileName;
|
||||
}
|
||||
|
||||
FileStream outFileStream = new FileStream(LocalFile, FileMode.OpenOrCreate);
|
||||
byte[] buf = new byte[inFileStream.Length];
|
||||
int byteCount;
|
||||
while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
|
||||
{
|
||||
outFileStream.Write(buf, 0, byteCount);
|
||||
}
|
||||
inFileStream.Flush();
|
||||
inFileStream.Close();
|
||||
outFileStream.Flush();
|
||||
outFileStream.Close();
|
||||
|
||||
ZipHelper.UnZip(LocalFile, zipedFolder);
|
||||
rel = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Sharefile_Error = ex.Message;
|
||||
}
|
||||
return rel;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将本地文件上传到远程服务器共享目录
|
||||
/// </summary>
|
||||
/// <param name="SourceFile">本地文件的绝对路径,包含扩展名</param>
|
||||
/// <param name="RemoteFile">远程服务器共享文件路径,不包含文件扩展名</param>
|
||||
/// <param name="RemoteFileName">上传到远程服务器后的文件扩展名</param>
|
||||
public static bool TransportLocalToRemote(string SourceFile, string RemoteFile, string RemoteFileName, out string Sharefile_Error) //src
|
||||
{
|
||||
Sharefile_Error = "";
|
||||
//string SourceFile, string LocalFile, string LocalFileName
|
||||
bool rel = false;
|
||||
try
|
||||
{
|
||||
FileStream inFileStream = new FileStream(SourceFile, FileMode.Open); //此处假定本地文件存在,不然程序会报错
|
||||
if (!Directory.Exists(RemoteFile)) //判断上传到的远程服务器路径是否存在
|
||||
{
|
||||
Directory.CreateDirectory(RemoteFile);
|
||||
}
|
||||
//上传到远程服务器共享文件夹后文件的绝对路径
|
||||
if (!RemoteFile.EndsWith(@"\"))
|
||||
{
|
||||
RemoteFile = RemoteFile + RemoteFileName;
|
||||
}
|
||||
else
|
||||
{
|
||||
RemoteFile = RemoteFile + "\\" + RemoteFileName;
|
||||
}
|
||||
FileStream outFileStream = new FileStream(RemoteFile, FileMode.OpenOrCreate);
|
||||
byte[] buf = new byte[inFileStream.Length];
|
||||
int byteCount;
|
||||
while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
|
||||
{
|
||||
outFileStream.Write(buf, 0, byteCount);
|
||||
}
|
||||
inFileStream.Flush();
|
||||
inFileStream.Close();
|
||||
outFileStream.Flush();
|
||||
outFileStream.Close();
|
||||
rel = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Sharefile_Error = ex.Message;
|
||||
}
|
||||
return rel;
|
||||
}
|
||||
}
|
||||
}
|
||||
173
Interface_WebAPI/SlMesDbIterface/MessageHanlder/Re.cs
Normal file
173
Interface_WebAPI/SlMesDbIterface/MessageHanlder/Re.cs
Normal file
@@ -0,0 +1,173 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using RecData;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace PLMTEST
|
||||
{
|
||||
public class Re
|
||||
{
|
||||
|
||||
|
||||
public static DataTable Analysis_DataObject(string jsonStr)
|
||||
{
|
||||
/*
|
||||
{
|
||||
"list": [
|
||||
{
|
||||
"errcode": 0,
|
||||
"errmsg": null,
|
||||
"objId": "01_18AC913FCA4A4DA99BDF01A99C232219",
|
||||
"objNo": "0100045006",
|
||||
"fname": null,
|
||||
"suffix": null,
|
||||
"hasAffine": null,
|
||||
"name": "油泵轴油封",
|
||||
"fsize": null,
|
||||
"fsizeStr": "未知",
|
||||
"type": "D",
|
||||
"tablename": "MPART",
|
||||
"smemo": null,
|
||||
"ctimestr": "2017-07-11 16:03",
|
||||
"mtimestr": "2020-12-21 15:36",
|
||||
"creator": "5914洪杰",
|
||||
"modifier": "11458戚亚克",
|
||||
"ver": "1",
|
||||
"stimestr": null,
|
||||
"etimestr": null,
|
||||
"extra": null,//这里加了俩字段:PTYPE(小类)、DTYPE(大类)
|
||||
"searchText": null
|
||||
}
|
||||
],
|
||||
"errcode": 0,
|
||||
"errmsg": null,
|
||||
"total": 1
|
||||
}
|
||||
*/
|
||||
|
||||
DataTable dt = new DataTable();
|
||||
dt.Columns.Add("errcode");
|
||||
dt.Columns.Add("errmsg");
|
||||
dt.Columns.Add("objId");
|
||||
dt.Columns.Add("objNo");
|
||||
dt.Columns.Add("fname");
|
||||
dt.Columns.Add("suffix");
|
||||
dt.Columns.Add("hasAffine");
|
||||
dt.Columns.Add("name");
|
||||
dt.Columns.Add("fsize");
|
||||
dt.Columns.Add("fsizeStr");
|
||||
dt.Columns.Add("type");
|
||||
dt.Columns.Add("tablename");
|
||||
dt.Columns.Add("smemo");
|
||||
dt.Columns.Add("ctimestr");
|
||||
dt.Columns.Add("mtimestr");
|
||||
dt.Columns.Add("creator");
|
||||
dt.Columns.Add("modifier");
|
||||
dt.Columns.Add("ver");
|
||||
dt.Columns.Add("stimestr");
|
||||
dt.Columns.Add("etimestr");
|
||||
dt.Columns.Add("extra");
|
||||
dt.Columns.Add("PTYPE");
|
||||
dt.Columns.Add("DTYPE");
|
||||
dt.Columns.Add("searchText");
|
||||
|
||||
|
||||
|
||||
var json = JsonConvert.DeserializeObject<JObject>(jsonStr);
|
||||
var errcode = json["errcode"].ToString();
|
||||
var errmsg = json["errmsg"].ToString();
|
||||
// var total = json["total"].ToString();
|
||||
if (errcode != "0")
|
||||
{
|
||||
dt = new DataTable();
|
||||
dt.Columns.Add("errcode");
|
||||
dt.Columns.Add("errmsg");
|
||||
// dt.Columns.Add("total");
|
||||
var dr = dt.NewRow();
|
||||
dr["errcode"] = errcode;
|
||||
dr["errmsg"] = errmsg;
|
||||
//dr["total"] = total;
|
||||
dt.Rows.Add(dr);
|
||||
return dt;
|
||||
}
|
||||
var array = json["list"];
|
||||
foreach (var a in array)
|
||||
{
|
||||
var _errcode = a["errcode"].ToString();
|
||||
var _errmsg = a["errmsg"].ToString();
|
||||
var objId = a["objId"].ToString();
|
||||
var objNo = a["objNo"].ToString();
|
||||
var fname = a["fname"].ToString();
|
||||
var suffix = a["suffix"].ToString();
|
||||
var hasAffine = a["hasAffine"].ToString();
|
||||
var name = a["name"].ToString();
|
||||
var fsize = a["fsize"].ToString();
|
||||
var fsizeStr = a["fsizeStr"].ToString();
|
||||
var type = a["type"].ToString();
|
||||
var tablename = a["tablename"].ToString();
|
||||
var smemo = a["smemo"].ToString();
|
||||
var ctimestr = a["ctimestr"].ToString();
|
||||
var mtimestr = a["mtimestr"].ToString();
|
||||
var creator = a["creator"].ToString();
|
||||
var modifier = a["modifier"].ToString();
|
||||
var ver = a["ver"].ToString();
|
||||
var stimestr = a["stimestr"].ToString();
|
||||
var etimestr = a["etimestr"].ToString();
|
||||
var extra_O = a["extra"];
|
||||
var extra = "-1";
|
||||
if (a["extra"] != null)
|
||||
{
|
||||
extra = a["extra"].ToString();
|
||||
}
|
||||
var PTYPE = GetVal.JToken_Value(extra_O, "PTYPE");
|
||||
var DTYPE = GetVal.JToken_Value(extra_O, "DTYPE");
|
||||
|
||||
var searchText = a["searchText"].ToString();
|
||||
|
||||
var dr = dt.NewRow();
|
||||
dr["errcode"] = _errcode;
|
||||
dr["errmsg"] = _errmsg;
|
||||
dr["objId"] = objId;
|
||||
dr["objNo"] = objNo;
|
||||
dr["fname"] = fname;
|
||||
dr["suffix"] = suffix;
|
||||
dr["hasAffine"] = hasAffine;
|
||||
dr["name"] = name;
|
||||
dr["fsize"] = fsize;
|
||||
dr["fsizeStr"] = fsizeStr;
|
||||
dr["type"] = type;
|
||||
dr["tablename"] = tablename;
|
||||
dr["smemo"] = smemo;
|
||||
|
||||
dr["ctimestr"] = ctimestr;
|
||||
dr["mtimestr"] = mtimestr;
|
||||
dr["creator"] = creator;
|
||||
dr["modifier"] = modifier;
|
||||
dr["ver"] = ver;
|
||||
|
||||
dr["stimestr"] = stimestr;
|
||||
dr["etimestr"] = etimestr;
|
||||
dr["extra"] = extra;
|
||||
dr["PTYPE"] = PTYPE;
|
||||
dr["DTYPE"] = DTYPE;
|
||||
dr["searchText"] = searchText;
|
||||
|
||||
dt.Rows.Add(dr);
|
||||
}
|
||||
|
||||
return dt;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
245
Interface_WebAPI/SlMesDbIterface/MessageHanlder/ZipHelper.cs
Normal file
245
Interface_WebAPI/SlMesDbIterface/MessageHanlder/ZipHelper.cs
Normal file
@@ -0,0 +1,245 @@
|
||||
using ICSharpCode.SharpZipLib.Zip;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ExternalDataSync.MessageHanlder
|
||||
{
|
||||
/// <summary>
|
||||
/// 适用于ZIP压缩
|
||||
/// </summary>
|
||||
public class ZipHelper
|
||||
{
|
||||
#region 压缩
|
||||
/// <summary>
|
||||
/// 压缩文件夹
|
||||
/// </summary>
|
||||
/// <param name="folderToZip">要压缩的文件夹路径</param>
|
||||
/// <param name="Stream">压缩前的Stream,方法执行后变为压缩完成后的文件</param>
|
||||
/// <param name="password">密码</param>
|
||||
/// <returns>是否成功</returns>
|
||||
public static bool ZipDirectoryToStream(string folderToZip, Stream Stream, string password = null)
|
||||
{
|
||||
return ZipDirectoryToZipStream(folderToZip, Stream, password) != null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 压缩文件夹
|
||||
/// </summary>
|
||||
/// <param name="folderToZip">要压缩的文件夹路径</param>
|
||||
/// <param name="Stream">压缩前的Stream,方法执行后变为压缩完成后的文件</param>
|
||||
/// <param name="password">密码</param>
|
||||
/// <returns>是否压缩成功返回ZipOutputStream,否则返回null</returns>
|
||||
public static ZipOutputStream ZipDirectoryToZipStream(string folderToZip, Stream Stream, string password = null)
|
||||
{
|
||||
if (!Directory.Exists(folderToZip))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
ZipOutputStream zipStream = new ZipOutputStream(Stream);
|
||||
zipStream.SetLevel(6);
|
||||
if (!string.IsNullOrEmpty(password))
|
||||
{
|
||||
zipStream.Password = password;
|
||||
}
|
||||
if (ZipDirectory(folderToZip, zipStream, ""))
|
||||
{
|
||||
zipStream.Finish();
|
||||
return zipStream;
|
||||
}
|
||||
GC.Collect(1);
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 递归压缩文件夹的内部方法
|
||||
/// </summary>
|
||||
/// <param name="folderToZip">要压缩的文件夹路径</param>
|
||||
/// <param name="zipStream">压缩输出流</param>
|
||||
/// <param name="parentFolderName">此文件夹的上级文件夹</param>
|
||||
/// <returns>是否成功</returns>
|
||||
private static bool ZipDirectory(string folderToZip, ZipOutputStream zipStream, string parentFolderName)
|
||||
{
|
||||
var crc = new ICSharpCode.SharpZipLib.Checksum.Crc32();
|
||||
|
||||
//这段是创建空文件夹,注释掉可以去掉空文件夹(因为在写入文件的时候也会创建文件夹)
|
||||
//if (!string.IsNullOrEmpty(parentFolderName))
|
||||
//{
|
||||
// ent = new ZipEntry(parentFolderName + "/");
|
||||
// zipStream.PutNextEntry(ent);
|
||||
// zipStream.Flush();
|
||||
//}
|
||||
|
||||
var files = Directory.GetFiles(folderToZip);
|
||||
foreach (string file in files)
|
||||
{
|
||||
byte[] buffer = File.ReadAllBytes(file);
|
||||
var ent = new ZipEntry(parentFolderName + "/" + Path.GetFileName(file));
|
||||
//ent.DateTime = File.GetLastWriteTime(file);//设置文件最后修改时间
|
||||
ent.DateTime = DateTime.Now;
|
||||
ent.Size = buffer.Length;
|
||||
|
||||
crc.Reset();
|
||||
crc.Update(buffer);
|
||||
|
||||
ent.Crc = crc.Value;
|
||||
zipStream.PutNextEntry(ent);
|
||||
zipStream.Write(buffer, 0, buffer.Length);
|
||||
}
|
||||
|
||||
var folders = Directory.GetDirectories(folderToZip);
|
||||
foreach (var folder in folders)
|
||||
{
|
||||
var _parentFolderName = parentFolderName + "\\" + folder.Substring(folder.LastIndexOf('\\') + 1);
|
||||
if (!ZipDirectory(folder, zipStream, _parentFolderName))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 压缩文件夹
|
||||
/// </summary>
|
||||
/// <param name="folderToZip">要压缩的文件夹路径</param>
|
||||
/// <param name="zipedFile">压缩文件完整路径</param>
|
||||
/// <param name="password">密码</param>
|
||||
/// <returns>是否成功</returns>
|
||||
public static bool ZipDirectory(string folderToZip, string zipedFile, string password = null)
|
||||
{
|
||||
var zipStream = ZipDirectoryToZipStream(folderToZip, new FileStream(zipedFile, FileMode.Create, FileAccess.Write), password);
|
||||
if (zipStream == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
zipStream.Close();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 压缩文件
|
||||
/// </summary>
|
||||
/// <param name="fileToZip">要压缩的文件全名</param>
|
||||
/// <param name="zipedFile">压缩后的文件名</param>
|
||||
/// <param name="password">密码</param>
|
||||
/// <returns>是否成功</returns>
|
||||
public static bool ZipFile(string fileToZip, string zipedFile, string password = null)
|
||||
{
|
||||
if (!File.Exists(fileToZip))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
var fs = File.OpenRead(fileToZip);
|
||||
byte[] buffer = new byte[fs.Length];
|
||||
fs.Read(buffer, 0, buffer.Length);
|
||||
fs.Close();
|
||||
|
||||
fs = File.Create(zipedFile);
|
||||
var ent = new ZipEntry(Path.GetFileName(fileToZip));
|
||||
using (var zipStream = new ZipOutputStream(fs))
|
||||
{
|
||||
if (!string.IsNullOrEmpty(password))
|
||||
{
|
||||
zipStream.Password = password;
|
||||
}
|
||||
zipStream.PutNextEntry(ent);
|
||||
zipStream.SetLevel(6);
|
||||
zipStream.Write(buffer, 0, buffer.Length);
|
||||
}
|
||||
|
||||
if (fs != null)
|
||||
{
|
||||
fs.Close();
|
||||
fs.Dispose();
|
||||
}
|
||||
|
||||
GC.Collect(1);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 压缩文件或文件夹
|
||||
/// </summary>
|
||||
/// <param name="fileToZip">要压缩的路径</param>
|
||||
/// <param name="zipedFile">压缩后的文件名</param>
|
||||
/// <param name="password">密码</param>
|
||||
/// <returns>是否成功</returns>
|
||||
public static bool Zip(string fileToZip, string zipedFile, string password = null)
|
||||
{
|
||||
if (Directory.Exists(fileToZip))
|
||||
{
|
||||
return ZipDirectory(fileToZip, zipedFile, password);
|
||||
}
|
||||
else if (File.Exists(fileToZip))
|
||||
{
|
||||
return ZipFile(fileToZip, zipedFile, password);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 解压
|
||||
/// <summary>
|
||||
/// 解压功能(解压压缩文件到指定目录)
|
||||
/// </summary>
|
||||
/// <param name="fileToUnZip">待解压的文件</param>
|
||||
/// <param name="zipedFolder">指定解压目标目录</param>
|
||||
/// <param name="password">密码</param>
|
||||
/// <returns>是否成功</returns>
|
||||
public static bool UnZip(string fileToUnZip, string zipedFolder, string password = null)
|
||||
{
|
||||
if (!System.IO.File.Exists(fileToUnZip))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!Directory.Exists(zipedFolder))
|
||||
{
|
||||
Directory.CreateDirectory(zipedFolder);
|
||||
}
|
||||
|
||||
if (!zipedFolder.EndsWith("\\"))
|
||||
{
|
||||
zipedFolder += "\\";
|
||||
}
|
||||
ZipEntry ent = null;
|
||||
using (var zipStream = new ZipInputStream(System.IO.File.OpenRead(fileToUnZip)))
|
||||
{
|
||||
if (!string.IsNullOrEmpty(password))
|
||||
{
|
||||
zipStream.Password = password;
|
||||
}
|
||||
while ((ent = zipStream.GetNextEntry()) != null)
|
||||
{
|
||||
if (ent.IsDirectory)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (string.IsNullOrEmpty(ent.Name))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
string fileName = zipedFolder + ent.Name.Replace('/', '\\');
|
||||
var index = ent.Name.LastIndexOf('/');
|
||||
if (index != -1)
|
||||
{
|
||||
string path = zipedFolder + ent.Name.Substring(0, index).Replace('/', '\\');
|
||||
System.IO.Directory.CreateDirectory(path);
|
||||
}
|
||||
var bytes = new byte[ent.Size];
|
||||
zipStream.Read(bytes, 0, bytes.Length);
|
||||
System.IO.File.WriteAllBytes(fileName, bytes);
|
||||
}
|
||||
}
|
||||
GC.Collect(1);
|
||||
return true;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user