Подтвердить что ты не робот

Получить размер файла на FTP в С#

Я хочу получить размер файла на 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();

EDIT: причина, по которой это не работает для меня, заключается в том, что мой FTP-сервер не поддерживает метод SIZE.

4b9b3361

Ответ 1

Попробуйте reqSize.Method = WebRequestMethods.Ftp.GetFileSize; вместо GetDateTimestamp

Это сработало для меня:

FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://servername/filepath"));
request.Proxy = null;
request.Credentials = new NetworkCredential("user", "password");
request.Method = WebRequestMethods.Ftp.GetFileSize;

FtpWebResponse response = (FtpWebResponse)request.GetResponse();
long size = response.ContentLength;
response.Close();

Ответ 2

//Простой и эффективный способ получить размер файла FTP.

var size = GetFtpFileSize (новый Uri ( "ftpURL" ), новый NetworkCredential ( "имя пользователя", "пароль" ));

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.
}