2010-11-14 175 views
11

我想在FTP上獲取文件的大小。在C中獲取FTP文件大小#

 //Get File Size 
     reqSize = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpPath + filePath)); 
     reqSize.Credentials = new NetworkCredential(Username, Password); 
     reqSize.Method = WebRequestMethods.Ftp.GetFileSize; 
     reqSize.UseBinary = true; 
     FtpWebResponse respSize = (FtpWebResponse)reqSize.GetResponse(); 
     long size = respSize.ContentLength; 
     respSize.Close(); 

我試過以下,但得到550錯誤。文件未找到/無法訪問。但是,下面的代碼工作...

   reqTime = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpPath + filePath)); 
       reqTime.Credentials = new NetworkCredential(Username, Password); 
       reqTime.Method = WebRequestMethods.Ftp.GetDateTimestamp; 
       reqTime.UseBinary = true; 
       FtpWebResponse respTime = (FtpWebResponse)reqTime.GetResponse(); 
       DateTime LastModified = respTime.LastModified; 
       respTime.Close(); 

編輯:這不是爲我工作的原因是我的FTP服務器不支持大小的方法。而不是GetDateTimestamp

回答

22

嘗試reqSize.Method = WebRequestMethods.Ftp.GetFileSize; 這爲我工作:

+0

比以前更好的意見:他需要從響應讀取數據,而不僅僅是獲得'ContentLength',我相信。無論哪種方式,內容長度將是0. – 2010-11-14 02:33:09

+0

這是一個複製粘貼錯誤 - 我更詳細地更新了我的問題。 – Jason 2010-11-14 02:34:40

+0

我可以在不下載文件的情況下獲得文件大小嗎?我只是不想下載這個文件,因爲它的巨大,如果它在本地相同的大小。 – Jason 2010-11-14 02:35:33

0

//最簡單和有效的方式來獲取FTP文件大小。 (新的Uri(「ftpURL」),新的NetworkCredential(「userName」,「password」));

public static long GetFtpFileSize(Uri requestUri, NetworkCredential networkCredential) 
{ 
    //Create ftpWebRequest object with given options to get the File Size. 
    var ftpWebRequest = GetFtpWebRequest(requestUri, networkCredential, WebRequestMethods.Ftp.GetFileSize); 

    try { return ((FtpWebResponse)ftpWebRequest.GetResponse()).ContentLength; } //Incase of success it'll return the File Size. 
    catch (Exception) { return default(long); } //Incase of fail it'll return default value to check it later. 
} 
public static FtpWebRequest GetFtpWebRequest(Uri requestUri, NetworkCredential networkCredential, string method = null) 
{ 
    var ftpWebRequest = (FtpWebRequest)WebRequest.Create(requestUri); //Create FtpWebRequest with given Request Uri. 
    ftpWebRequest.Credentials = networkCredential; //Set the Credentials of current FtpWebRequest. 

    if (!string.IsNullOrEmpty(method)) 
     ftpWebRequest.Method = method; //Set the Method of FtpWebRequest incase it has a value. 
    return ftpWebRequest; //Return the configured FtpWebRequest. 
}