c# ftp 判斷目錄是否存在和建立文件夾

  工做中項目一直使用的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);
            }

        }
相關文章
相關標籤/搜索