2014年10月7日 星期二

C# FTP根目錄底下,指定副檔名,檔案計算數量

//ftpPath:FTP位置
//ftpUser:FTP帳號
//ftpPassword:FTP密碼
//strExtension:副檔案名稱
//intFileCount:回傳計算結果

public bool CheckFTPCount(string ftpPath, string ftpUser, string ftpPassword, string strExtension, ref int intFileCount)
        {
            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 = "";
                intFileCount = 0;
                while (line != null)
                {
                    //讀取目錄下檔案名稱及根目錄名稱
                    line = reader.ReadLine();
                   //如有包含指定副檔名,即可記錄
                    if (line.Contains(strExtension))
                    {
                        intFileCount++;
                    }

                }
            }
            catch (Exception)
            {
                success = false;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (webResponse != null)
                {
                    webResponse.Close();
                }
            }
            return success;
        }

沒有留言:

張貼留言