C#在FTP服务器上无法获取文件大小

时间:2013-02-22 14:38:23

标签: c# ftp filesize

当我想在我的ftp服务器上获取文件的大小时,我什么也得不到。

有人在代码中看到问题吗?

在我看来,方法很好

班级:

public string getFileSize(string fileName)
{
    try
    {
        ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + fileName);
        ftpRequest.Credentials = new NetworkCredential(user, pass);
        ftpRequest.UseBinary = true;
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = true;
        ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;
        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
        ftpStream = ftpResponse.GetResponseStream();
        StreamReader ftpReader = new StreamReader(ftpStream);
        string fileInfo = null;
        try { while (ftpReader.Peek() != -1) { fileInfo = ftpReader.ReadToEnd(); } }
        catch (Exception ex) { Console.WriteLine(ex.ToString()); }
        ftpReader.Close();
        ftpStream.Close();
        ftpResponse.Close();
        ftpRequest = null;
        return fileInfo;
    }
    catch (Exception ex) { Console.WriteLine(ex.ToString()); }
    return "";
}

过程:

ftp ftpClientCheckFile = new ftp(@"ftp://******.******.fr", "***********", "********");
string ftpfileSize = ftpClientCheckFile.getFileSize(fileName);

if (ftpfileSize == localfilesize)
{
  this.Invoke(new Action(() => { MessageBox.Show(this, "*********", "***", MessageBoxButtons.OK, MessageBoxIcon.Information); }));
  ftpClientCheckFile = null;
}
else
{
  this.Invoke(new Action(() => { MessageBox.Show(this, "***** ", "*******", MessageBoxButtons.OK, MessageBoxIcon.Information); }));
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您需要使用ContentLength属性来获取文件大小

Console.WriteLine(ftpResponse.ContentLength.ToString());

某些ftp服务器不支持getfilesize,因此您必须使用ListDirectoryDetails