C#如何取得ftp上面的所有文件夹里面的所有文件名,求源码。。。。
发布网友
发布时间:2022-05-05 13:43
我来回答
共1个回答
热心网友
时间:2023-10-08 17:36
连接方法:
string ftpServerIP = "";
string ftpUserID = "";
string ftpPassword = "";
string TempPath = Path.GetTempPath();
FtpWebRequest reqFTP;
DataTable dt;
private void Connect(String path)//连接ftp
{
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
}
catch (Exception){
Response.Write("<srcipt>alert('连接失败!')</script>");
}
获取方法:
private string[] GetFileList(string path, string WRMethods)
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
try
{
Connect(path);
reqFTP.Method = WRMethods;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf('\n'), 1);
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception)
{
downloadFiles = null;
return downloadFiles;
}
}
调用:
string[] str = GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectoryDetails);
数组就是ftp文件夹下的所有文件名,如果要判断ftp根下面的是文件还是文件夹。需要解字符串才行!