目的:获取ftp上一个路径下所有文件的列表
ftp信息如下:
ftp://192.168.1.3
用户名:test
密码:test
我要获取如下路径下的文件列表(文件名,不包含后缀)
ftp://192.168.1.3/TV/PATTERN
该路径下会有几十至几百个如下文件
L100.pt
L101.pt
L102.pt
....
我要获取
L100
L101
L102
...
4 个解决方案
#1
/// <summary>
/// 根据ftp路径返回目录下的文件名称 不带扩展名
/// </summary>
/// <param name="ftpDir"></param>
/// <param name="userName"></param>
/// <param name="passWord"></param>
/// <returns></returns>
public static ArrayList GetFileNames(string ftpDir, string userName, string passWord)
{
var fileNames = new ArrayList();
var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(ftpDir));
reqFtp.UsePassive = false;
reqFtp.UseBinary = true;
//reqFTP.EnableSsl = true;//加密方式传送数据 FTP 服务器要支持
reqFtp.Credentials = new NetworkCredential(userName, passWord);
reqFtp.Method = WebRequestMethods.Ftp.ListDirectory;
var response = (FtpWebResponse)reqFtp.GetResponse();
var reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
string fileName = reader.ReadLine();
while (fileName != null)
{
fileNames.Add(Path.GetFileNameWithoutExtension(fileName));
fileName = reader.ReadLine();
}
reader.Close();
response.Close();
//var fileNames = reader.ReadToEnd();
reader.Close();
response.Close();
return fileNames;
}
调用代码如下.亲测
var filanames = Ftp.GetFileNames(@"ftp://192.168.1.3", "test", "test");
var sb = new StringBuilder();
foreach (string n in filanames)
{
sb.AppendLine(n);
}
MessageBox.Show(sb.ToString());
#2
太棒了,测试通过。非常感谢。
不过向这样的代码不行:
var fileNames = new ArrayList();
必须改成如下
ArrayList fileNames = new ArrayList();
谢谢
#3
var 是.net 3.0以后才有的,.net 2.0无法使用
#4
1 楼可用。Thanks
#1
/// <summary>
/// 根据ftp路径返回目录下的文件名称 不带扩展名
/// </summary>
/// <param name="ftpDir"></param>
/// <param name="userName"></param>
/// <param name="passWord"></param>
/// <returns></returns>
public static ArrayList GetFileNames(string ftpDir, string userName, string passWord)
{
var fileNames = new ArrayList();
var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(ftpDir));
reqFtp.UsePassive = false;
reqFtp.UseBinary = true;
//reqFTP.EnableSsl = true;//加密方式传送数据 FTP 服务器要支持
reqFtp.Credentials = new NetworkCredential(userName, passWord);
reqFtp.Method = WebRequestMethods.Ftp.ListDirectory;
var response = (FtpWebResponse)reqFtp.GetResponse();
var reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
string fileName = reader.ReadLine();
while (fileName != null)
{
fileNames.Add(Path.GetFileNameWithoutExtension(fileName));
fileName = reader.ReadLine();
}
reader.Close();
response.Close();
//var fileNames = reader.ReadToEnd();
reader.Close();
response.Close();
return fileNames;
}
调用代码如下.亲测
var filanames = Ftp.GetFileNames(@"ftp://192.168.1.3", "test", "test");
var sb = new StringBuilder();
foreach (string n in filanames)
{
sb.AppendLine(n);
}
MessageBox.Show(sb.ToString());
#2
太棒了,测试通过。非常感谢。
不过向这样的代码不行:
var fileNames = new ArrayList();
必须改成如下
ArrayList fileNames = new ArrayList();
谢谢
#3
var 是.net 3.0以后才有的,.net 2.0无法使用
#4
1 楼可用。Thanks