这几天做了一个关于FTP与服务器之间文件互相传输的Windows服务,本地开发的时候非常顺利,很快就开发完成了,可是将服务部署到服务器上的时候,却出现了许多的意外,让人防不胜防,今天就总结一下我在工作过程中遇到的问题。
先上我的代码吧,然后再讲解(代码主要是记录给我自己看的,可以直接跳过看问题):
1.这是Program.cs文件的代码:
using System.ServiceProcess; namespace ECI.SW.HandleStorageMessageService { static class Program { /// <summary> /// 应用程序的主入口点。 /// <author>Asa</author> /// <createDate>2019/06/20</createDate> /// </summary> static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { // 实例化我的服务类 new HandleStorageMessageService() }; // 运行服务类 ServiceBase.Run(ServicesToRun); #region test code begin // 控制台方式调用服务类中的方法 // ServiceExcute.GygHandleMessage(); #endregion test code end } } }
2.HandleStorageMessageService类中的代码
using ECI.SW.HandleStorageMessageService.Model; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using PL.Base; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.ServiceProcess; using System.Text; using System.Timers; using System.Xml; namespace ECI.SW.HandleStorageMessageService { /// <summary> /// 电子口岸发送企业集装箱堆场数据服务 /// <author>Asa</author> /// <createDate>2019/06/13</createDate> /// </summary> public partial class HandleStorageMessageService : ServiceBase { /// <summary> /// 构造函数 /// <author>Asa</author> /// <createDate>2019/06/20</createDate> /// </summary> public HandleStorageMessageService() { InitializeComponent(); } /// <summary> /// 服务启动时执行 /// <author>Asa</author> /// <createDate>2019/06/20</createDate> /// </summary> /// <param name="args">args</param> protected override void OnStart(string[] args) { // 控制台方式调试时注释掉 //ServiceExcute.Init(); } /// <summary> /// 服务停止时执行 /// <author>Asa</author> /// <createDate>2019/06/20</createDate> /// </summary> protected override void OnStop() { } } /// <summary> /// 处理堆场信息 /// <author>Asa</author> /// <createDate>2019/06/14</createDate> /// </summary> public class ServiceExcute { // 定义一个定时器(控制台方式调试时注释掉) private static Timer timer; /// <summary> /// 初始化定时器(控制台方式调试时注释掉) /// <author>Asa</author> /// <createDate>2019/06/14</createDate> /// </summary> public static void Init() { try { // 数据来源 string DataSource = EciConfig.Read("DataSource"); // timer执行间隔时间 int seconds = Convert.ToInt32(EciConfig.Read("ReadFileTime")) * 60000; timer = new Timer(seconds); if (DataSource.Equals("GYG")) { timer.Elapsed += new ElapsedEventHandler(GygHandleMessage); } // 是否使用定时器 timer.Enabled = true; } catch (Exception ex) { Log.Write("init出错:" + ex.Message, "initCatch"); } } /// <summary> /// 果园港(Gyg)堆场数据文件处理 object sender, EventArgs e /// <author>Asa</author> /// <createDate>2019/06/14</createDate> /// </summary> /// <param name="sender">sender</param> /// <param name="e">e</param> public static void GygHandleMessage(object sender, EventArgs e) { try { // 字母转ASCII码,这里不需要 // AlphabetToNumber(); #region 读取配置信息,声明必要的对象--BEGIN(这里因为我需要将读取的Excel转为XML保存到服务器,所以配置了很多地址,按自己需要配置) // 读取FTP访问地址 string ftpPath = EciConfig.Read("ftpPath"); // 读取ftp访问用户名 string userName = EciConfig.Read("userName"); // 读取ftp访问密码 string pwd = EciConfig.Read("pwd"); // 读取excel文件保存的路径 string saveExcelFilePath = EciConfig.Read("saveExcelFilePath"); // 读取xml文件保存的路径 string saveXmlFilePath = EciConfig.Read("saveXmlFilePath"); // 读取单一窗口服务器上回执报文保存的地址 string readXmlFilePath = EciConfig.Read("readXmlFilePath"); // 读取sheetname string sheetName = EciConfig.Read("sheetName"); // 实例化一个Datatable对象接收Excel转换的Datatable(这里顺便可以学习npoi读取Excel并转Datatable的方法) DataTable excelDt = new DataTable(); #endregion 读取配置信息,声明必要的对象--END #region 处理堆场数据--BEGIN // 连接FTP,这里使用了一个我的FTPhelper类,等会儿会贴上来 Common.FTP.FtpHelper ftpHelper = new Common.FTP.FtpHelper(ftpPath, "", userName, pwd); // 获取FTP上的文件列表 string[] fileNameArray = ftpHelper.GetFileList(""); // 判断文件列表是否为空 if (fileNameArray != null) { // 遍历文件列表,从FTP服务器下载对应文件 foreach (string fileName in fileNameArray) { #region 判断是否是Excel文件 // 获取文件拓展名 string extensionName = fileName.Substring(fileName.LastIndexOf(".")); // 获取文件名 string fileNameNoExtension = fileName.Substring(0, fileName.LastIndexOf(".")); // 判断文件是否是Excel文件 if (!extensionName.Equals(".xls") && !extensionName.Equals(".xlsx")) { continue; } #endregion #region 下载堆场数据Excel文件--BEGIN // 判断保存Excel文件的路径是否存在,如果不存在就创建该地址 if (!Directory.Exists(saveExcelFilePath)) Directory.CreateDirectory(saveExcelFilePath); // 判断文件是否已下载,如果已下载则跳过 if (File.Exists(saveExcelFilePath + "/" + fileName)) continue; // 根据文件名下载文件 ftpHelper.Download(saveExcelFilePath, fileName); #endregion 下载堆场数据Excel文件--END #region 处理堆场数据Excel文件(这一块是我对读取到的FTP文件做的我自己的业务需求处理,可以不看)--BEGIN #region XML头信息实体--BEGIN // 当前时间 DateTime datetimeNow = DateTime.Now; // 报文编码 string msgId = "01" + "CNCQI800028" + datetimeNow.ToString("yyyyMMddHHmmssfff"); // 实例化XML头实体对象 SwStorageMessageHead swStorageMessageHead = new SwStorageMessageHead(); // 报文编码 swStorageMessageHead.MSG_ID = msgId; // 报文类型 swStorageMessageHead.MSG_TYPE = "CSA01"; // 关卡代码 swStorageMessageHead.CUSTOMS_CODE = "8007"; // 作业场所编号 swStorageMessageHead.SUPV_LOCT_CODE = "CNCQI800028"; // 报文发送时间 swStorageMessageHead.DECL_DATE = datetimeNow.ToString(); // 申报数据类型 swStorageMessageHead.DECLARE_DATE_TYPE = "0"; // 申报数据报文总数 swStorageMessageHead.TOTAL_MSG_NO = "1"; // 当前报文序号 swStorageMessageHead.CUR_MSG_NO = "1"; // 堆场信息XML文件头数据插入SQL语句 StringBuilder insertHeadBuilder = new StringBuilder(); BuildHeadInsertSql(insertHeadBuilder, swStorageMessageHead); try { // 初始化connectionstring连接字符串对象 EciServer.InitFramework(); // 插入XML头数据 DBHelper.ExecuteNoneQuery(insertHeadBuilder.ToString()); } catch (Exception ex) { Log.Write("SwStorageMessageHead插入失败:" + ex.Message, "InsertErr"); } #endregion XML头信息实体--END #region XML基础信息写入--BEGIN // 实例化一个操作XML文件的对象 XmlDocument xmldoc = new XmlDocument(); // 实例化一个填写版本等信息的XML节点对象(创建具有指定值的xmldeclaration节点) XmlNode versionNode = xmldoc.CreateXmlDeclaration("1.0", "UTF-8", ""); // 将指定的节点添加到子节点列表的末尾 xmldoc.AppendChild(versionNode); // 创建xmldocument中的单个节点(根节点) XmlNode rootNode = xmldoc.CreateElement("ContaDeclareInfo"); // 将根节点添加到子节点列表的末尾 xmldoc.AppendChild(rootNode); #endregion XML基础信息写入--END #region xml信息写入--BEGIN // 创建XML头节点 CreateHeadNode(xmldoc, rootNode, swStorageMessageHead); // 创建XML--Declaratioin节点 XmlNode declareationNode = xmldoc.CreateNode(XmlNodeType.Element, "Declaratioin", null); try { // 调用读取Excel转换为Datatable的方法 excelDt = ReadExcelToDataTable(saveExcelFilePath + "\\" + fileName, sheetName); } catch (Exception dtEx) { Log.Write("Excel转换为Datatable出错:" + dtEx.Message, "ToDatatableErr"); } if (excelDt != null && excelDt.Rows.Count > 0) // 执行数据插入list表并生成对应Declaratioin--XML节点 InsertListDbAndCreateListXmlExecute(excelDt, msgId, xmldoc, declareationNode); // 将Declaratioin节点添加到根节点 rootNode.AppendChild(declareationNode); #endregion xml信息写入--END #region 保存创建的XML文件--BEGIN try { xmldoc.Save(saveXmlFilePath + "\\" + fileNameNoExtension + ".xml"); } catch (Exception ex) { Log.Write("保存xml文件失败:" + ex.Message, "saveXmlErr"); } #endregion 保存创建的XML文件--END #endregion 处理堆场数据Excel文件--END } } #endregion 处理堆场数据--END // 处理回执报文信息 HandleResponseXml(readXmlFilePath, ftpHelper); } catch (Exception ex) { Log.Write("UnExpectedError:" + ex.Message, "UnExpectedError"); } } // 这下面都是我的工具方法,可以不看 // 字母转换为ASCII码数字 public static string AlphabetToNumber() { byte[] array = new byte[1]; //定义一组数组array array = Encoding.ASCII.GetBytes("E"); //string转换的字母 int asciicode = (short)(array[0]); string ascii = Convert.ToString(asciicode); //将转换一的ASCII码转换成string型 return ascii; } /// <summary> /// 读取Excel文件并转化为Datatable /// <author>Asa</author> /// <createDate>2019/06/20</createDate> /// </summary> /// <param name="filePath">文件地址</param> /// <param name="sheetname">sheet名称</param> /// <returns></returns> public static DataTable ReadExcelToDataTable(string filePath, string sheetname) { #region 实例化必要的对象--BEGIN // 声明一个IWorkbook对象 IWorkbook workbook = null; // 实例化一个ISheet对象,用来接收读取到的sheet ISheet sheet = null; // 实例化一个Datatable对象 DataTable dt = new DataTable(); // 判断文件是否存在,不存在返回空 if (!File.Exists(filePath)) return null; // 将读取到的文件转为文件流 FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); #endregion 实例化必要的对象--END #region 根据Excel文件的版本使用不同的IWorkbook对象--BEGIN // 判断读取到的Excel文件的版本 if (filePath.IndexOf(".xlsx") > 0) { // 2007版本 workbook = new XSSFWorkbook(fs); } else if (filePath.IndexOf(".xls") > 0) { // 2003版本 workbook = new HSSFWorkbook(fs); } #endregion 根据Excel文件的版本使用不同的IWorkbook对象--END // 接收读取到的sheet sheet = workbook.GetSheet(sheetname); #region 对sheet表进行处理==>转换为Datatable--BEGIN var rows = sheet.GetRowEnumerator(); while (rows.MoveNext()) { IRow row = rows.Current as IRow; if (row.RowNum == 0) { row.Cells.ForEach(cell => { dt.Columns.Add(cell.StringCellValue); }); } else { var dr = dt.NewRow(); for (int i = 0; i < row.Cells.Count; i++) { dr[i] = row.Cells[i].ToString(); } dt.Rows.Add(dr); } } #endregion 对sheet表进行处理==>转换为Datatable--END return dt; } /// <summary> /// 处理回执报文 /// <author>Asa</author> /// <createDate>2019/06/19</createDate> /// </summary> /// <param name="readXmlFilePath">读取回执报文的路径</param> /// <param name="fileNameArray">FTP服务器上现有的文件名列表</param> /// <param name="ftpHelper">FTP工具类对象</param> public static void HandleResponseXml(string readXmlFilePath, Common.FTP.FtpHelper ftpHelper) { // 获取文件列表 string[] fileNameArr = ftpHelper.GetFileList(""); // 读取所有的回执报文XML文件 DirectoryInfo receiptXmlList = new DirectoryInfo(readXmlFilePath); // 遍历文件列表,获取XML文件 foreach (FileInfo receiptXml in receiptXmlList.GetFiles("*.xml")) { // 实例化一个XML操作对象 XmlDocument xmldoc = new XmlDocument(); // 通过URL加载XML文件 xmldoc.Load(receiptXml.FullName); // 定义一个标记判断报文是否已存在 bool isExists = false; #region 上传读取的回执XML文件--BEGIN try { // 遍历FTP文件列表 foreach (string fileName in fileNameArr) { // 判断回执报文是否已存在,已存在则不上传 if (fileName.Equals(receiptXml.Name)) { isExists = true; break; } } // 如果回执报文不存在,则上传 if (!isExists) ftpHelper.Upload(receiptXml.FullName); else continue; } catch (Exception ex) { Log.Write("上传xml回执文件失败:" + ex.Message, "saveXmlErr"); } #endregion 上传读取的回执XML文件--END #region 回执报文数据入库--BEGIN #region 获取回执报文XML节点--BEGIN // 报文编码 XmlNode msgId = xmldoc.SelectSingleNode("//MsgId"); // 报文类型 XmlNode msgType = xmldoc.SelectSingleNode("//MsgType"); // 关卡代码 XmlNode customsCode = xmldoc.SelectSingleNode("//CustomsCode"); // 作业场所编码 XmlNode supvLoctCode = xmldoc.SelectSingleNode("//SupvLoctCode"); // 报文发送时间 XmlNode declDate = xmldoc.SelectSingleNode("//DeclDate"); // 回执结果 XmlNode result = xmldoc.SelectSingleNode("//Result"); // 备注信息 XmlNode remark = xmldoc.SelectSingleNode("//Remark"); #endregion 回执报文数据入库--END #region 回执报文表头实体赋值--BEGIN // 回执报文表头实体赋值 SwStorageResponseHead swStorageResponseHead = new SwStorageResponseHead(); swStorageResponseHead.MSG_ID = msgId.InnerText; swStorageResponseHead.MSG_TYPE = msgType.InnerText; swStorageResponseHead.CUSTOMS_CODE = customsCode.InnerText; swStorageResponseHead.SUPV_LOCT_CODE = supvLoctCode.InnerText; swStorageResponseHead.DECL_DATE = declDate.InnerText; // 实例化一个stringbuilder对象用来拼接表头插入语句 StringBuilder insertResponseHeadBuilder = new StringBuilder(); BuildResponseHeadInserSql(insertResponseHeadBuilder, swStorageResponseHead); #endregion 回执报文表头实体赋值--END #region 执行回执报文表头数据入库--BEGIN try { // 初始化connectionstring连接字符串对象 EciServer.InitFramework(); // 插入XML头数据 DBHelper.ExecuteNoneQuery(insertResponseHeadBuilder.ToString()); } catch (Exception ex) { Log.Write("SwStorageResponseHead插入失败:" + ex.Message, "InsertErr"); } #endregion 执行回执报文表头数据入库--END #region 回执报文表体实体赋值--BEGIN // 回执报文表体赋值 SwStorageResponseList swStorageResponseList = new SwStorageResponseList(); swStorageResponseList.MSG_ID = msgId.InnerText; swStorageResponseList.RESULT = result.InnerText; swStorageResponseList.REMARK = remark.InnerText; // 实例化一个stringbuilder对象拼接表体插入语句 StringBuilder insertResponseListBuilder = new StringBuilder(); BuildResponseListInserSql(insertResponseListBuilder, swStorageResponseList); #endregion 回执报文表体实体赋值--END #region 执行回执报文表体数据入库--BEGIN try { // 初始化connectionstring连接字符串对象 EciServer.InitFramework(); // 插入XML头数据 DBHelper.ExecuteNoneQuery(insertResponseListBuilder.ToString()); } catch (Exception ex) { Log.Write("SwStorageResponseList插入失败:" + ex.Message, "InsertErr"); } #endregion 执行回执报文表体数据入库--END #endregion 回执报文数据入库--END } } /// <summary> /// 执行数据插入list表并生成对应Declaratioin--XML节点 /// <author>Asa</author> /// <createDate>2019/06/18</createDate> /// </summary> /// <param name="ds">读取Excel生成的dataset</param> /// <param name="msgId">报文编码</param> /// <param name="xmldoc">xmldocument对象</param> /// <param name="declareationNode">Declaratioin节点</param> public static void InsertListDbAndCreateListXmlExecute(DataTable excelDt, string msgId, XmlDocument xmldoc, XmlNode declareationNode) { // 遍历dataset,读取Excel中的堆场数据并存入表中 for (int i = 3; i < excelDt.Rows.Count; i++) { #region XML数据信息实体--BEGIN SwStorageMessageList swStorageMessageList = new SwStorageMessageList(); // 报文编码 swStorageMessageList.MSG_ID = msgId; // 集装箱号 swStorageMessageList.CONTA_ID = excelDt.Rows[i][4].ToString(); // 判断是否是列名,如果是列名就跳过这一行 if (swStorageMessageList.CONTA_ID.Equals("箱号") || swStorageMessageList.CONTA_ID.NullOrEmpty()) continue; // 集装箱尺寸 swStorageMessageList.CONTA_TYPE_CODE = excelDt.Rows[i][5].ToString(); // 箱位代码 swStorageMessageList.SEAT = excelDt.Rows[i][15].ToString(); // 将箱位代码转换为正确的格式 swStorageMessageList.SEAT = swStorageMessageList.SEAT.Replace("-", "/0"); #region 内外贸标识--BEGIN swStorageMessageList.TRADE_MARK = excelDt.Rows[i][2].ToString(); if (swStorageMessageList.TRADE_MARK.Equals("内贸")) swStorageMessageList.TRADE_MARK = "D"; else if (swStorageMessageList.TRADE_MARK.Equals("外贸")) swStorageMessageList.TRADE_MARK = "I"; else swStorageMessageList.TRADE_MARK = "O"; #endregion 内外贸标识--END #region 进出口标识--BEGIN swStorageMessageList.IE_FLAG = excelDt.Rows[i][10].ToString(); if (swStorageMessageList.IE_FLAG.Equals("进口")) swStorageMessageList.IE_FLAG = "I"; else if (swStorageMessageList.IE_FLAG.Equals("出口")) swStorageMessageList.IE_FLAG = "E"; #endregion 进出口标识--END // 拼箱状态 swStorageMessageList.CONTA_MARK = ""; // 装载状态 swStorageMessageList.LOAD_MARK = excelDt.Rows[i][7].ToString(); // 危品柜状态 swStorageMessageList.DANGER_MARK = ""; // 进场时间 swStorageMessageList.ENTRANCE_DATE = excelDt.Rows[i][23].ToString(); // 出场时间 swStorageMessageList.DEPART_TRUE_DATE = ""; // 当前状态 swStorageMessageList.WORK_MARK = "A"; // 数据处理标识 swStorageMessageList.DATA_DEAL_FLAG = "A"; // 提单号 swStorageMessageList.BILL_NO = excelDt.Rows[i][14].ToString(); // 报关单号 swStorageMessageList.ENTRY_ID = ""; // 转关单号 swStorageMessageList.PRE_NO = ""; // 多式联运单号 swStorageMessageList.MT_APPLY_NO = ""; // 备注 swStorageMessageList.REMARK = "备注信息"; // 计划状态 swStorageMessageList.PLAN_STATUS = excelDt.Rows[i][1].ToString(); // 是否中转 swStorageMessageList.IS_TRANSFER = excelDt.Rows[i][3].ToString(); // 箱型 swStorageMessageList.CONTA_TYPE = excelDt.Rows[i][6].ToString(); // 箱货类 swStorageMessageList.CONTA_GOODS_TYPE = excelDt.Rows[i][8].ToString(); // 货柜 swStorageMessageList.CONTAINER = excelDt.Rows[i][9].ToString(); // 箱主 swStorageMessageList.CONTA_OWNER = excelDt.Rows[i][11].ToString(); // 船公司 swStorageMessageList.BOAT_COMPANY = excelDt.Rows[i][12].ToString(); // 代理公司 swStorageMessageList.AGENT_COMPANY = excelDt.Rows[i][13].ToString(); // 铅封 swStorageMessageList.LEAD_SEALING = excelDt.Rows[i][16].ToString(); // 破损说明 swStorageMessageList.DAMAGE_DESCRIPTION = excelDt.Rows[i][17].ToString(); // 破损代码 swStorageMessageList.DAMAGE_CODE = excelDt.Rows[i][18].ToString(); // 进口船名 swStorageMessageList.I_BOAT_NAME = excelDt.Rows[i][19].ToString(); // 进口航次 swStorageMessageList.I_BOAT_VOYAGENO = excelDt.Rows[i][20].ToString(); // 出口船名 swStorageMessageList.E_BOAT_NAME = excelDt.Rows[i][21].ToString(); // 出口航次 swStorageMessageList.E_BOAT_VOYAGENO = excelDt.Rows[i][22].ToString(); // 堆存天 swStorageMessageList.STORAGE_DATE = excelDt.Rows[i][24].ToString(); // 货名 swStorageMessageList.GOODS_NAME = excelDt.Rows[i][25].ToString(); // 总重 swStorageMessageList.TOTAL_WEIGHT = excelDt.Rows[i][26].ToString(); // 货重 swStorageMessageList.GOODS_WEIGHT = excelDt.Rows[i][27].ToString(); // 堆场表体数据插入SQL语句 StringBuilder insertBodyBuilder = new StringBuilder(); BuildListInsertSql(insertBodyBuilder, swStorageMessageList); try { // 初始化connectionstring连接字符串对象 EciServer.InitFramework(); DBHelper.ExecuteNoneQuery(insertBodyBuilder.ToString()); } catch (Exception ex) { Log.Write("SwStorageMessageList插入失败:" + ex.Message, "InsertErr"); } #endregion XML数据信息实体--END // 创建XML-->Declaration节点的子节点(Data)信息 CreateDataNode(xmldoc, declareationNode, swStorageMessageList); } } /// <summary> /// 创建XML头节点的信息 /// <author>Asa</author> /// <createDate>2019/06/18</createDate> /// </summary> /// <param name="xmldoc">XmlDocument对象</param> /// <param name="rootNode">根节点</param> /// <param name="swStorageMessageHead">头信息实体对象</param> public static void CreateHeadNode(XmlDocument xmldoc, XmlNode rootNode, SwStorageMessageHead swStorageMessageHead) { // 声明一个装载XML头信息的节点 XmlNode headNode = xmldoc.CreateNode(XmlNodeType.Element, "Head", null); // 报文编码节点 XmlNode msgIdNode = xmldoc.CreateNode(XmlNodeType.Element, "MsgId", null); // 报文类型节点 XmlNode msgTypeNode = xmldoc.CreateNode(XmlNodeType.Element, "MsgType", null); // 关卡代码节点 XmlNode customsCodeNode = xmldoc.CreateNode(XmlNodeType.Element, "CustomsCode", null); // 作业场所编号节点 XmlNode supvLoctCodeNode = xmldoc.CreateNode(XmlNodeType.Element, "SupvLoctCode", null); // 报文发送时间节点 XmlNode declDateNode = xmldoc.CreateNode(XmlNodeType.Element, "DeclDate", null); // 数据申报类型节点 XmlNode declareDataTypeNode = xmldoc.CreateNode(XmlNodeType.Element, "DeclareDataType", null); // 申报数据报文总数节点 XmlNode totalMsgNoNode = xmldoc.CreateNode(XmlNodeType.Element, "TotalMsgNo", null); // 当前报文序号节点 XmlNode curMsgNoNode = xmldoc.CreateNode(XmlNodeType.Element, "CurMsgNo", null); // 给各个头信息子节点赋值 msgIdNode.InnerText = swStorageMessageHead.MSG_ID; msgTypeNode.InnerText = swStorageMessageHead.MSG_TYPE; customsCodeNode.InnerText = swStorageMessageHead.CUSTOMS_CODE; supvLoctCodeNode.InnerText = swStorageMessageHead.SUPV_LOCT_CODE; declDateNode.InnerText = swStorageMessageHead.DECL_DATE; declareDataTypeNode.InnerText = swStorageMessageHead.DECLARE_DATE_TYPE; totalMsgNoNode.InnerText = swStorageMessageHead.TOTAL_MSG_NO; curMsgNoNode.InnerText = swStorageMessageHead.CUR_MSG_NO; // 将各个头信息子节点添加到头信息根节点 headNode.AppendChild(msgIdNode); headNode.AppendChild(msgTypeNode); headNode.AppendChild(customsCodeNode); headNode.AppendChild(supvLoctCodeNode); headNode.AppendChild(declDateNode); headNode.AppendChild(declareDataTypeNode); headNode.AppendChild(totalMsgNoNode); headNode.AppendChild(curMsgNoNode); // 将头节点添加到根节点 rootNode.AppendChild(headNode); } /// <summary> /// 创建XML数据节点的信息 /// <author>Asa</author> /// <createDate>2091/06/18</createDate> /// </summary> /// <param name="xmldoc">XmlDocument对象</param> /// <param name="declareationNode">Declaration节点</param> /// <param name="swStorageMessageList"></param> public static void CreateDataNode(XmlDocument xmldoc, XmlNode declareationNode, SwStorageMessageList swStorageMessageList) { // 声明一个装载XML-->Data信息的节点 XmlNode dataNode = xmldoc.CreateNode(XmlNodeType.Element, "Data", null); // 集装箱号 XmlNode contaId = xmldoc.CreateNode(XmlNodeType.Element, "ContaId", null); // 集装箱尺寸 XmlNode contaTypeCode = xmldoc.CreateNode(XmlNodeType.Element, "ContaTypeCode", null); // 箱位代码 XmlNode seat = xmldoc.CreateNode(XmlNodeType.Element, "Seat", null); // 内外贸标识 XmlNode tradeMark = xmldoc.CreateNode(XmlNodeType.Element, "TradeMark", null); // 进出口标识 XmlNode iEFlag = xmldoc.CreateNode(XmlNodeType.Element, "IEFlag", null); // 拼箱状态 XmlNode contaMark = xmldoc.CreateNode(XmlNodeType.Element, "ContaMark", null); // 装载状态 XmlNode loadMark = xmldoc.CreateNode(XmlNodeType.Element, "LoadMark", null); // 危品柜状态 XmlNode dangerMark = xmldoc.CreateNode(XmlNodeType.Element, "DangerMark", null); // 进场时间 XmlNode entranceDate = xmldoc.CreateNode(XmlNodeType.Element, "EntranceDate", null); // 出场时间 XmlNode departtureDate = xmldoc.CreateNode(XmlNodeType.Element, "DeparttureDate", null); // 当前状态 XmlNode workMark = xmldoc.CreateNode(XmlNodeType.Element, "WorkMark", null); // 数据处理标识 XmlNode dataDealFlag = xmldoc.CreateNode(XmlNodeType.Element, "DataDealFlag", null); // 提单号 XmlNode billNo = xmldoc.CreateNode(XmlNodeType.Element, "BillNo", null); // 报关单号 XmlNode entryId = xmldoc.CreateNode(XmlNodeType.Element, "EntryId", null); // 转关单号 XmlNode preNo = xmldoc.CreateNode(XmlNodeType.Element, "PreNo", null); // 多式联运单号 XmlNode mtApplyBlNo = xmldoc.CreateNode(XmlNodeType.Element, "MtApplyBlNo", null); // 备注信息 XmlNode remark = xmldoc.CreateNode(XmlNodeType.Element, "Remark", null); // 给各个Data信息子节点赋值 contaId.InnerText = swStorageMessageList.CONTA_ID; contaTypeCode.InnerText = swStorageMessageList.CONTA_TYPE_CODE; seat.InnerText = swStorageMessageList.SEAT; tradeMark.InnerText = swStorageMessageList.TRADE_MARK; iEFlag.InnerText = swStorageMessageList.IE_FLAG; contaMark.InnerText = swStorageMessageList.CONTA_MARK; loadMark.InnerText = swStorageMessageList.LOAD_MARK; dangerMark.InnerText = swStorageMessageList.DANGER_MARK; entranceDate.InnerText = swStorageMessageList.ENTRANCE_DATE; departtureDate.InnerText = swStorageMessageList.DEPART_TRUE_DATE; workMark.InnerText = swStorageMessageList.WORK_MARK; dataDealFlag.InnerText = swStorageMessageList.DATA_DEAL_FLAG; billNo.InnerText = swStorageMessageList.BILL_NO; entryId.InnerText = swStorageMessageList.ENTRY_ID; preNo.InnerText = swStorageMessageList.PRE_NO; mtApplyBlNo.InnerText = swStorageMessageList.MT_APPLY_NO; remark.InnerText = swStorageMessageList.REMARK; // 将各个信息节点加入Data节点 dataNode.AppendChild(contaId); dataNode.AppendChild(contaTypeCode); dataNode.AppendChild(seat); dataNode.AppendChild(tradeMark); dataNode.AppendChild(iEFlag); dataNode.AppendChild(contaMark); dataNode.AppendChild(loadMark); dataNode.AppendChild(dangerMark); dataNode.AppendChild(entranceDate); dataNode.AppendChild(departtureDate); dataNode.AppendChild(workMark); dataNode.AppendChild(dataDealFlag); dataNode.AppendChild(billNo); dataNode.AppendChild(entryId); dataNode.AppendChild(preNo); dataNode.AppendChild(mtApplyBlNo); dataNode.AppendChild(remark); // 将data节点加入declareation节点 declareationNode.AppendChild(dataNode); } /// <summary> /// 构建list表插入SQL语句 /// <author>Asa</author> /// <createDate>2019/06/18</createDate> /// </summary> /// <param name="insertBodyBuilder">构建插入语句的对象</param> /// <param name="swStorageMessageList">插入信息实体</param> public static void BuildListInsertSql(StringBuilder insertBodyBuilder, SwStorageMessageList swStorageMessageList) { insertBodyBuilder.Append("INSERT INTO SW_STORAGE_MESSAGE_LIST("); insertBodyBuilder.Append("MSG_ID,CONTA_ID,CONTA_TYPE_CODE,SEAT,TRADE_MARK,IE_FLAG,CONTA_MARK,"); insertBodyBuilder.Append("LOAD_MARK,DANGER_MARK,ENTRANCE_DATE,DEPART_TRUE_DATE,WORK_MARK,"); insertBodyBuilder.Append("DATA_DEAL_FLAG,BILL_NO,ENTRY_ID,PRE_NO,MT_APPLY_NO,REMARK,"); insertBodyBuilder.Append("PLAN_STATUS,IS_TRANSFER,CONTA_TYPE,CONTA_GOODS_TYPE,CONTAINER,"); insertBodyBuilder.Append("CONTA_OWNER,BOAT_COMPANY,AGENT_COMPANY,LEAD_SEALING,DAMAGE_DESCRIPTION,"); insertBodyBuilder.Append("DAMAGE_CODE,I_BOAT_NAME,I_BOAT_VOYAGENO,E_BOAT_NAME,E_BOAT_VOYAGENO,STORAGE_DATE,"); insertBodyBuilder.Append("GOODS_NAME,TOTAL_WEIGHT,GOODS_WEIGHT) VALUES("); insertBodyBuilder.Append("'" + swStorageMessageList.MSG_ID + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.CONTA_ID + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.CONTA_TYPE_CODE + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.SEAT + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.TRADE_MARK + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.IE_FLAG + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.CONTA_MARK + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.LOAD_MARK + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.DANGER_MARK + "',"); insertBodyBuilder.Append("to_date('" + swStorageMessageList.ENTRANCE_DATE + "', 'yyyy-MM-dd HH24:mi:ss'),"); //("'" + swStorageMessageList.ENTRANCE_DATE + "'"); insertBodyBuilder.Append("to_date('" + swStorageMessageList.DEPART_TRUE_DATE + "', 'yyyy-MM-dd HH24:mi:ss'),"); //("'" + swStorageMessageList.DEPART_TRUE_DATE + "'"); insertBodyBuilder.Append("'" + swStorageMessageList.WORK_MARK + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.DATA_DEAL_FLAG + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.BILL_NO + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.ENTRY_ID + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.PRE_NO + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.MT_APPLY_NO + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.REMARK + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.PLAN_STATUS + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.IS_TRANSFER + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.CONTA_TYPE + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.CONTA_GOODS_TYPE + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.CONTAINER + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.CONTA_OWNER + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.BOAT_COMPANY + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.AGENT_COMPANY + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.LEAD_SEALING + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.DAMAGE_DESCRIPTION + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.DAMAGE_CODE + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.I_BOAT_NAME + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.I_BOAT_VOYAGENO + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.E_BOAT_NAME + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.E_BOAT_VOYAGENO + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.STORAGE_DATE + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.GOODS_NAME + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.TOTAL_WEIGHT + "',"); insertBodyBuilder.Append("'" + swStorageMessageList.GOODS_WEIGHT + "')"); } /// <summary> /// 构建head表插入SQL语句 /// <author>Asa</author> /// <createDate>2019/06/8</createDate> /// </summary> /// <param name="insertHeadBuilder">构建插入语句的对象</param> /// <param name="swStorageMessageHead">插入信息实体</param> public static void BuildHeadInsertSql(StringBuilder insertHeadBuilder, SwStorageMessageHead swStorageMessageHead) { insertHeadBuilder.Append("INSERT INTO SW_STORAGE_MESSAGE_HEAD("); insertHeadBuilder.Append("MSG_ID,MSG_TYPE,CUSTOMS_CODE,SUPV_LOCT_CODE,"); insertHeadBuilder.Append("DECL_DATE,DECLARE_DATE_TYPE,TOTAL_MSG_NO,CUR_MSG_NO) "); insertHeadBuilder.Append("VALUES('" + swStorageMessageHead.MSG_ID + "',"); insertHeadBuilder.Append("'" + swStorageMessageHead.MSG_TYPE + "',"); insertHeadBuilder.Append("'" + swStorageMessageHead.CUSTOMS_CODE + "',"); insertHeadBuilder.Append("'" + swStorageMessageHead.SUPV_LOCT_CODE + "',"); insertHeadBuilder.Append("to_date('" + swStorageMessageHead.DECL_DATE + "', 'yyyy-MM-dd HH24:mi:ss'),"); insertHeadBuilder.Append("'" + swStorageMessageHead.DECLARE_DATE_TYPE + "',"); insertHeadBuilder.Append("'" + swStorageMessageHead.TOTAL_MSG_NO + "',"); insertHeadBuilder.Append("'" + swStorageMessageHead.CUR_MSG_NO + "')"); } /// <summary> /// 构建响应报文表头插入SQL语句 /// <author>Asa</author> /// <createDate>2019/06/20</createDate> /// </summary> /// <param name="insertResponseHeadBuilder">拼接数据插入sql语句StringBuilder对象</param> /// <param name="swStorageResponseHead">SwStorageResponseHead实体对象</param> public static void BuildResponseHeadInserSql(StringBuilder insertResponseHeadBuilder, SwStorageResponseHead swStorageResponseHead) { insertResponseHeadBuilder.Append("INSERT INTO SW_STORAGE_RESPONSE_HEAD(MSG_ID,"); insertResponseHeadBuilder.Append("MSG_TYPE,CUSTOMS_CODE,SUPV_LOCT_CODE,DECL_DATE) VALUES("); insertResponseHeadBuilder.Append("'" + swStorageResponseHead.MSG_ID + "',"); insertResponseHeadBuilder.Append("'" + swStorageResponseHead.MSG_TYPE + "',"); insertResponseHeadBuilder.Append("'" + swStorageResponseHead.CUSTOMS_CODE + "',"); insertResponseHeadBuilder.Append("'" + swStorageResponseHead.SUPV_LOCT_CODE + "',"); insertResponseHeadBuilder.Append("to_date('" + swStorageResponseHead.DECL_DATE + "', 'yyyy-MM-dd HH24:mi:ss'))");//("'" + swStorageResponseHead.DECL_DATE + "')"); } /// <summary> /// 构建响应报文表体插入SQL语句 /// <author>Asa</author> /// <createDate>2019/06/20</createDate> /// </summary> /// <param name="insertResponseListBuilder">拼接数据插入sql语句StringBuilder对象</param> /// <param name="swStorageResponseList">SwStorageResponseList实体对象</param> public static void BuildResponseListInserSql(StringBuilder insertResponseListBuilder, SwStorageResponseList swStorageResponseList) { insertResponseListBuilder.Append("INSERT INTO SW_STORAGE_RESPONSE_LIST(MSG_ID,"); insertResponseListBuilder.Append("RESULT,REMARK) VALUES("); insertResponseListBuilder.Append("'" + swStorageResponseList.MSG_ID + "',"); insertResponseListBuilder.Append("'" + swStorageResponseList.RESULT + "',"); insertResponseListBuilder.Append("'" + swStorageResponseList.REMARK + "')"); } } }
代码主要是记录给我自己看的,现在说说我在部署过程中遇到的问题吧:
当我部署上去的时候,启动服务,但是我从FTP下载文件却一直没成功,下载的方法一直报出操作超时,我改了超时时间也没用
想了一下,会不会是FTP的数据端口--20没有开放出来,我用浏览器访问了一下FTP,却又能成功的访问到,排除了这个问题
后来和同事研究了很久,才想到可能是FTP的两种传输模式引起的问题,于是我试了一下,将FTP传输模式()改为了被动式,
果然就能成功下载FTP上的文件了。(早先所有客户端都使用主动模式,而且工作的很好,而现在因为客户端防火墙的存在,将会关闭一些
端口,这样主动模式将会失败。在这种情况下就要使用被动模式,但是一些端口也可能被服务器的防火墙封掉。不过因为ftp服务器需要它的ftp服 务连接到一定数量的客户端,所以他们总是支持被动模式的。这就是我们为什么要使用被动模式的原意,为了确保数据可以正确的传输,使用 被动 模式要明显优于主动模式。)
附上我的FTP工具类,需要的小伙伴可以学习一下:
using System; using System.IO; using System.Net; using System.Text; using System.Web; namespace ECI.SW.Common.FTP { /// <summary> /// <author>Asa</author> /// <createDate>2017-03-07</createDate> /// <description>FTP工具类</description> /// </summary> public class FtpHelper { private readonly string _ftpPassword; private readonly string _ftpServerIp; private readonly string _ftpUserId; private string _ftpRemotePath; private string _ftpUri; /// <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 + "/"; } /// <summary> /// 上传 /// </summary> /// <param name="filename">文件名称(含路径)</param> public void Upload(string filename) { var fileInf = new FileInfo(filename); var uri = _ftpUri + fileInf.Name; var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(uri)); reqFtp.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword); reqFtp.KeepAlive = false; reqFtp.Method = WebRequestMethods.Ftp.UploadFile; reqFtp.UseBinary = true; reqFtp.KeepAlive = true; reqFtp.UsePassive = true; reqFtp.ContentLength = fileInf.Length; reqFtp.ReadWriteTimeout = 60000; reqFtp.Timeout = 60000; var buffLength = 2048; var buff = new byte[buffLength]; var fs = fileInf.OpenRead(); try { var strm = reqFtp.GetRequestStream(); var contentLen = fs.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } strm.Close(); fs.Close(); } catch (Exception ex) { throw new Exception("Ftphelper Upload Error --> " + ex.Message); } } /// <summary> /// 上传 /// </summary> /// <param name="fileInf">提供对客户端已上载的单独文件的访问</param> public void Upload(HttpPostedFile fileInf) { var uri = _ftpUri + fileInf.FileName; var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(uri)); reqFtp.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword); reqFtp.KeepAlive = false; reqFtp.Method = WebRequestMethods.Ftp.UploadFile; reqFtp.UseBinary = true; reqFtp.UsePassive = false; reqFtp.ContentLength = fileInf.ContentLength; var buffLength = 2048; var buff = new byte[buffLength]; var fs = fileInf.InputStream; try { var strm = reqFtp.GetRequestStream(); var contentLen = fs.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } strm.Close(); fs.Close(); } catch (Exception ex) { throw new Exception("Ftphelper Upload Error --> " + ex.Message); } } /// <summary> /// 下载 /// </summary> /// <param name="filePath">保存文件的本地路径</param> /// <param name="fileName">要下载的文件名</param> public void Download(string filePath, string fileName) { try { var outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create); var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(_ftpUri + fileName)); reqFtp.Method = WebRequestMethods.Ftp.DownloadFile; reqFtp.UseBinary = true; reqFtp.KeepAlive = true; reqFtp.UsePassive = true; reqFtp.Timeout = 60000; reqFtp.ReadWriteTimeout = 60000; reqFtp.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword); var response = (FtpWebResponse)reqFtp.GetResponse(); var ftpStream = response.GetResponseStream(); var cl = response.ContentLength; var bufferSize = 2048; var buffer = new byte[bufferSize]; if (ftpStream != null) { var readCount = ftpStream.Read(buffer, 0, bufferSize); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); } } if (ftpStream != null) ftpStream.Close(); outputStream.Close(); response.Close(); } catch (Exception ex) { throw new Exception("FtpHelper Download Error --> " + ex.Message); } } /// <summary> /// 删除文件 /// </summary> /// <param name="fileName">文件名</param> public void Delete(string fileName) { try { var uri = _ftpUri + fileName; var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(uri)); reqFtp.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword); reqFtp.KeepAlive = false; reqFtp.Method = WebRequestMethods.Ftp.DeleteFile; reqFtp.UsePassive = false; var result = string.Empty; var response = (FtpWebResponse)reqFtp.GetResponse(); var size = response.ContentLength; var datastream = response.GetResponseStream(); if (datastream != null) { var sr = new StreamReader(datastream); result = sr.ReadToEnd(); sr.Close(); } if (datastream != null) datastream.Close(); response.Close(); } catch (Exception ex) { throw new Exception("FtpHelper Delete Error --> " + ex.Message + " 文件名:" + fileName); } } /// <summary> /// 删除文件夹 /// </summary> /// <param name="folderName">文件夹名称</param> public void RemoveDirectory(string folderName) { try { var uri = _ftpUri + folderName; var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(uri)); reqFtp.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword); reqFtp.KeepAlive = false; reqFtp.Method = WebRequestMethods.Ftp.RemoveDirectory; reqFtp.UsePassive = false; var result = string.Empty; var response = (FtpWebResponse)reqFtp.GetResponse(); var size = response.ContentLength; var datastream = response.GetResponseStream(); if (datastream != null) { var sr = new StreamReader(datastream); result = sr.ReadToEnd(); sr.Close(); } if (datastream != null) datastream.Close(); response.Close(); } catch (Exception ex) { throw new Exception("FtpHelper Delete Error --> " + ex.Message + " 文件名:" + folderName); } } /// <summary> /// 获取当前目录下明细(包含文件和文件夹) /// </summary> /// <returns></returns> public string[] GetFilesDetailList() { try { var result = new StringBuilder(); var ftp = (FtpWebRequest)WebRequest.Create(new Uri(_ftpUri)); ftp.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword); ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; ftp.UsePassive = false; var response = ftp.GetResponse(); var reader = new StreamReader(response.GetResponseStream(), Encoding.Default); var line = reader.ReadLine(); while (line != null) { result.Append(line); result.Append("\n"); line = reader.ReadLine(); } result.Remove(result.ToString().LastIndexOf("\n"), 1); reader.Close(); response.Close(); return result.ToString().Split('\n'); } catch (Exception ex) { //downloadFiles = null; throw new Exception("FtpHelper Error --> " + ex.Message); } } /// <summary> /// 获取当前目录下文件列表(仅文件) /// </summary> /// <returns></returns> public string[] GetFileList(string mask) { var result = new StringBuilder(); try { var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(_ftpUri)); reqFtp.UseBinary = true; reqFtp.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword); reqFtp.Method = WebRequestMethods.Ftp.ListDirectory; reqFtp.KeepAlive = true; reqFtp.UsePassive = true; reqFtp.Timeout = 60000; var response = reqFtp.GetResponse(); var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); var line = reader.ReadLine(); while (line != null) { if ((mask.Trim() != string.Empty) && (mask.Trim() != "*.*")) { var mask_ = mask.Substring(0, mask.IndexOf("*")); if (line.Substring(0, mask_.Length) == mask_) { result.Append(line); result.Append("\n"); } } else { result.Append(line); result.Append("\n"); } line = reader.ReadLine(); } result.Remove(result.ToString().LastIndexOf('\n'), 1); reader.Close(); response.Close(); return result.ToString().Split('\n'); } catch (Exception ex) { if (ex.Message.Trim() != "远程服务器返回错误: (550) 文件不可用(例如,未找到文件,无法访问文件)。") throw new Exception("FtpHelper GetFileList Error --> " + ex.Message); return null; } } /// <summary> /// 获取当前目录下所有的文件夹列表(仅文件夹) /// </summary> /// <returns></returns> public string[] GetDirectoryList() { var drectory = GetFilesDetailList(); var m = string.Empty; foreach (var str in drectory) { var dirPos = str.IndexOf("<DIR>"); if (dirPos > 0) { /*判断 Windows 风格*/ m += str.Substring(dirPos + 5).Trim() + "\n"; } else if (str.Trim().Substring(0, 1).ToUpper() == "D") { /*判断 Unix 风格*/ var dir = str.Substring(54).Trim(); if ((dir != ".") && (dir != "..")) m += dir + "\n"; } } char[] n = { '\n' }; return m.Split(n); } /// <summary> /// 判断当前目录下指定的子目录是否存在 /// </summary> /// <param name="remoteDirectoryName">指定的目录名</param> public bool DirectoryExist(string remoteDirectoryName) { var dirList = GetDirectoryList(); foreach (var str in dirList) if (str.Trim() == remoteDirectoryName.Trim()) return true; return false; } /// <summary> /// 判断当前目录下指定的文件是否存在 /// </summary> /// <param name="remoteFileName">远程文件名</param> public bool FileExist(string remoteFileName) { var fileList = GetFileList("*.*"); foreach (var str in fileList) if (str.Trim() == remoteFileName.Trim()) return true; return false; } /// <summary> /// 创建文件夹 /// </summary> /// <param name="dirName"></param> public void MakeDir(string dirName) { try { // dirName = name of the directory to create. var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(_ftpUri + dirName)); reqFtp.Method = WebRequestMethods.Ftp.MakeDirectory; reqFtp.UseBinary = true; reqFtp.UsePassive = false; reqFtp.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword); var response = (FtpWebResponse)reqFtp.GetResponse(); var ftpStream = response.GetResponseStream(); if (ftpStream != null) ftpStream.Close(); response.Close(); } catch (Exception ex) { throw new Exception("FtpHelper MakeDir Error --> " + ex.Message); } } /// <summary> /// 获取指定文件大小 /// </summary> /// <param name="filename">文件名称</param> /// <returns></returns> public long GetFileSize(string filename) { long fileSize = 0; try { var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(_ftpUri + filename)); reqFtp.Method = WebRequestMethods.Ftp.GetFileSize; reqFtp.UseBinary = true; reqFtp.UsePassive = false; reqFtp.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword); var response = (FtpWebResponse)reqFtp.GetResponse(); var ftpStream = response.GetResponseStream(); fileSize = response.ContentLength; ftpStream.Close(); response.Close(); } catch (Exception ex) { throw new Exception("FtpHelper GetFileSize Error --> " + ex.Message); } return fileSize; } /// <summary> /// 改名 /// </summary> /// <param name="currentFilename">当前文件名</param> /// <param name="newFilename">新文件名</param> public void ReName(string currentFilename, string newFilename) { try { var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(_ftpUri + currentFilename)); reqFtp.Method = WebRequestMethods.Ftp.Rename; reqFtp.RenameTo = newFilename; reqFtp.UseBinary = true; reqFtp.UsePassive = false; reqFtp.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword); var response = (FtpWebResponse)reqFtp.GetResponse(); var ftpStream = response.GetResponseStream(); if (ftpStream != null) ftpStream.Close(); response.Close(); } catch (Exception ex) { throw new Exception("FtpHelper ReName Error --> " + ex.Message); } } /// <summary> /// 移动文件 /// </summary> /// <param name="currentFilename">当前文件名</param> /// <param name="newDirectory">新文件夹</param> public void MovieFile(string currentFilename, string newDirectory) { ReName(currentFilename, newDirectory); } /// <summary> /// 切换当前目录 /// </summary> /// <param name="directoryName">文件夹名称</param> /// <param name="isRoot">true 绝对路径 false 相对路径</param> public void GotoDirectory(string directoryName, bool isRoot) { if (isRoot) _ftpRemotePath = directoryName; else _ftpRemotePath += directoryName + "/"; _ftpUri = "ftp://" + _ftpServerIp + "/" + _ftpRemotePath + "/"; } } }