C# FTP客户端 如何获取服务器上某文件的大小

2024-12-26 14:23:09
推荐回答(1个)
回答1:

///


/// 获取ftp服务器上指定文件夹的文件列表(包含文件大小)
///

///
///
///
///
///
public Dictionary GetFTPList(string ServerIP, string USERID, string PassWord, string path)
{
Dictionary dic = new Dictionary();
if (path == null)
path = "";
FtpWebRequest reqFtp;
try
{
reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ServerIP + "/" + path));
reqFtp.KeepAlive = false;
reqFtp.UseBinary = true; //指定ftp数据传输类型为 二进制
reqFtp.Credentials = new NetworkCredential(USERID, PassWord); //设置于ftp通讯的凭据
reqFtp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; //指定操作方式
WebResponse response = reqFtp.GetResponse(); //获取一个FTP响应
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("GB2312")); //读取响应流
string line = reader.ReadLine();
while (line != null)
{
if (line != "." && line != "..")
{
int end = line.LastIndexOf(' ');
int start = line.IndexOf(" ");
string filename = line.Substring(end + 1);
if (filename.Contains("."))
{
line = line.Replace(filename, "");
dic.Add(filename.Trim(), int.Parse(line.Substring(start).Trim()));
}
}
line = reader.ReadLine();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

return dic;
}

文件夹或者某一文件都适用