我想要獲取每個文件在FTP服務器上的文件名,文件大小和上次修改時間,然後用它填充listView。C#使用ftpRequest獲取完整文件列表的速度很慢
它工作得很好,直到我切換FTP主機,現在它真的很慢,儘管新的主機在真正的FTP客戶端速度一樣快。
明顯的原因是爲什麼?
另外,每次發送登錄憑證真的需要嗎?
我使用第一種方法來獲得一個字符串數組,然後遍歷它並使用在各個項目上第二個獲得文件大小:
public static string[] GetFileList()
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
FtpWebRequest request;
try
{
request = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://mysite.se/"));
request.UseBinary = true;
request.Credentials = new NetworkCredential(settings.Username, settings.Password);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.UseBinary = true;
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
// to remove the trailing '\n'
result.Remove(result.ToString().LastIndexOf('\n'), 1);
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
downloadFiles = null;
return downloadFiles;
}
}
public static int GetFileSize(string file)
{
//MessageBox.Show("getting filesize...");
StringBuilder result = new StringBuilder();
FtpWebRequest request;
try
{
request = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://mysite.se/" + file));
request.UseBinary = true;
request.Credentials = new NetworkCredential(settings.Username, settings.Password);
request.Method = WebRequestMethods.Ftp.GetFileSize;
int dataLength = (int)request.GetResponse().ContentLength;
return dataLength;
}
catch (Exception ex)
{
//System.Windows.Forms.MessageBox.Show(ex.Message);
return 1337;
}
}