首頁 > 軟體

C#中ftp檢測目錄是否存在和建立資料夾的實現

2022-07-10 18:01:57

C# ftp判斷目錄是否存在,不存在則自動建立資料夾

        /// <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);
        }
        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();
        }

定義ftp地址:private string ftpServerIP = "IP:埠";

         /// <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);
            }
        }

到此這篇關於C#中ftp檢測目錄是否存在和建立資料夾的實現的文章就介紹到這了,更多相關C# ftp檢測目錄存在內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com