C#不';无法在FTP服务器上获取文件大小
本文关键字:服务器 FTP 获取 文件大小 | 更新日期: 2023-09-27 18:00:39
当我想在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); }));
}
谢谢你的帮助。
您需要使用ContentLength属性来获取文件大小
Console.WriteLine(ftpResponse.ContentLength.ToString());
有些ftp服务器不支持getfilesize
,因此您将不得不使用ListDirectoryDetails