工做中项目一直使用的ftp上传日志文件出现了问题,新的服务器搭建好后,日志没法上传。正好来学习一下ftp。服务器
程序中的流程是,一个计时器,每分钟检测配置文件中本地日志文件路径下有没有日志文件,若是有就上传到服务器上去,而后把本地的文件删掉。日志以日期为单位,天天一个文件夹,以后是日志类型,按类型分文件夹。上传以前先检测服务器上是否存在该文件夹,若是不存在则建立一个文件。学习
下面是代码。(只放ftp那部分)ui
/// <summary> /// 判断文件的目录是否存,不存则建立 /// </summary> /// <param name="destFilePath">本地文件目录</param> public void CheckDirectoryAndMakeMyWilson3(string destFilePath) { string fullDir = destFilePath.IndexOf(':') > 0 ? destFilePath.Substring(destFilePath.IndexOf(':') + 1) : destFilePath; fullDir = fullDir.Replace('\\', '/'); string[] dirs = fullDir.Split('/');//解析出路径上全部的文件名 string curDir = "/"; for (int i = 0; i < dirs.Length; i++)//循环查询每个文件夹 { if (dirs[i] == "") continue; string dir = dirs[i]; //若是是以/开始的路径,第一个为空 if (dir != null && dir.Length > 0) { try { CheckDirectoryAndMakeMyWilson2(curDir, dir); curDir += dir + "/"; } catch (Exception) { } } } }
public void CheckDirectoryAndMakeMyWilson2(string rootDir, string remoteDirName) { if (!DirectoryExist(rootDir, remoteDirName))//判断当前目录下子目录是否存在 MakeDir(rootDir + "\\" + remoteDirName); }
/// <summary> /// 判断当前目录下指定的子目录是否存在 /// </summary> /// <param name="RemoteDirectoryName">指定的目录名</param> public bool DirectoryExist(string rootDir, string RemoteDirectoryName) { string[] dirList = GetDirectoryList(rootDir);//获取子目录 if (dirList.Length > 0) { foreach (string str in dirList) { if (str.Trim() == RemoteDirectoryName.Trim()) { return true; } } } return false; }
//获取子目录 public string[] GetDirectoryList(string dirName) { string[] drectory = GetFilesDetailList(dirName); List<string> strList = new List<string>(); if (drectory.Length > 0) { foreach (string str in drectory) { if (str.Trim().Length == 0) continue; //会有两种格式的详细信息返回 //一种包含<DIR> //一种第一个字符串是drwxerwxx这样的权限操做符号 //如今写代码包容两种格式的字符串 if (str.Trim().Contains("<DIR>")) { strList.Add(str.Substring(39).Trim()); } else { if (str.Trim().Substring(0, 1).ToUpper() == "D") { strList.Add(str.Substring(55).Trim()); } } } } return strList.ToArray(); }
/// <summary> /// 得到文件明晰 /// </summary> /// <param name="path"></param> /// <returns></returns> public string[] GetFilesDetailList(string path) { return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectoryDetails); }
//都调用这个 //上面的代码示例了如何从ftp服务器上得到文件列表 private string[] GetFileList(string path, string WRMethods) { StringBuilder result = new StringBuilder(); try { Connect(path);//创建FTP链接 reqFTP.Method = WRMethods; reqFTP.KeepAlive = false; WebResponse response = reqFTP.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名 string line = reader.ReadLine(); while (line != null) { result.Append(line); result.Append("\n"); line = reader.ReadLine(); } // to remove the trailing '' '' if (result.ToString() != "") { result.Remove(result.ToString().LastIndexOf("\n"), 1); } reader.Close(); response.Close(); return result.ToString().Split('\n'); } catch (Exception ex) { throw new Exception("获取文件列表失败。缘由: " + ex.Message); } }
//链接ftp private void Connect(String path) { // 根据uri建立FtpWebRequest对象 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path)); // 指定数据传输类型 reqFTP.Method = System.Net.WebRequestMethods.Ftp.UploadFile; reqFTP.UseBinary = true; reqFTP.UsePassive = false;//表示链接类型为主动模式 // ftp用户名和密码 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); }
/// <summary> /// 建立目录 /// </summary> /// <param name="dirName"></param> public void MakeDir(string dirName) { try { string uri = "ftp://" + ftpServerIP + "/" + dirName; Connect(uri);//链接 reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory; reqFTP.KeepAlive = false; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); response.Close(); } catch (Exception ex) { throw new Exception("建立文件失败,缘由: " + ex.Message); } }