2014年10月7日 星期二

C# FTP 目錄底下檔案搜尋


// ftpPath:FTP 位置
//ftpUser:FTP帳號
//ftpPassword:FTP密碼
//strExtension:被搜尋的副檔名
//strFileList:回傳的檔案名稱(數量要先計算,要先new好該有的數量,另一篇會教如何計算數量)
計算方式

public bool CheckFTPFileList(string ftpPath, string ftpUser, string ftpPassword, string strExtension, ref string[] strFileList)
        {
            bool success = false;
            FtpWebRequest ftpWebRequest = null;
            WebResponse webResponse = null;
            StreamReader reader = null;
            try
            {
                string url = ftpPath;
                //new 一個FTP連線
                ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
                //建立FTP連線
                ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
                //選擇通訊協定方法
                ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectory;
                //完成要求動做後,關閉連線
                ftpWebRequest.KeepAlive = false;
                // 取得FTP回應
                webResponse = ftpWebRequest.GetResponse();
                //讀取FTP資訊
                reader = new StreamReader(webResponse.GetResponseStream());

                string line = "";
                int intFileCount = 0;
                while (line != null)
                {
                    //讀取目錄下檔案名稱及根目錄名稱
                    line = reader.ReadLine();
                   //如有包含指定副檔名,即可記錄
                    if (line.Contains(strExtension))
                    {
                        strFileList[intFileCount] = line;
                        intFileCount++;
                    }
                }
            }
            catch (Exception)
            {
                success = false;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (webResponse != null)
                {
                    webResponse.Close();
                }
            }
            return success;
        }

沒有留言:

張貼留言