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

时间:2022-07-07 12:31:53
/// <summary>
/// 获取ftp服务器上指定文件夹的文件列表(包含文件大小)
/// </summary>
/// <param name="ServerIP"></param>
/// <param name="USERID"></param>
/// <param name="PassWord"></param>
/// <param name="path"></param>
/// <returns></returns>
public Dictionary<string, int> GetFTPList(string ServerIP, string USERID, string PassWord, string path)
{
Dictionary<string, int> dic = new Dictionary<string, int>();
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)
{

}

return dic;
}