ftp文件下载
我写了一个控制台应用下载的程序,测试的时候只能下载一个.txt文件,但是我要把所有的.txt文件下载下来应该怎么做呀,代码应该怎么该呢,做过类似程序的各位大侠教教我吧public static bool Download(string downloadUrl, string TargetPath, string UserName, string Password)
{
//downloadUrl下载ftp目录: ftp//127.0.0.1/abc.txt , TargetPath本地存档目录,UserName登录用户名 , Password密码
Stream responseStream = null;
FileStream fileStream = null;
StreamReader reader = null;
try
{
FtpWebRequest downloadRequest = (FtpWebRequest)WebRequest.Create(downloadUrl);
downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile;
if (UserName.Length > 0) {
NetworkCredential nc = new NetworkCredential(UserName, Password);
downloadRequest.Credentials = nc;//设置帐号
}
FtpWebResponse downloadResponse = (FtpWebResponse)downloadRequest.GetResponse();
responseStream = downloadResponse.GetResponseStream();
string fileName = Path.GetFileName(downloadRequest.RequestUri.AbsolutePath);
if (fileName.Length == 0)
{
reader = new StreamReader(responseStream);
throw new Exception(reader.ReadToEnd());
}
else
{
fileStream = File.Create(TargetPath + @"\" + fileName);
//fileStream = File.Create(TargetPath + fileName);
byte[] buffer = new byte[1024];
int bytesRead;
while (true)
{//开始写文件
bytesRead = responseStream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
fileStream.Write(buffer, 0, bytesRead);
}
}
return true;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
if (reader != null)
reader.Close();
else if (responseStream != null)
responseStream.Close();
if (fileStream != null)
fileStream.Close();
}
} --------------------编程问答-------------------- 不顶就要沉啦 --------------------编程问答-------------------- 如果你知道所有txt文件名称和地址,你用个循环不就可以了。 --------------------编程问答-------------------- 遍历所以你需要下载的文件+判断条件 --------------------编程问答-------------------- 把你的downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile; 改成
downloadRequest.Method = WebRequestMethods.Ftp.ListDirectory;这样就可以获取目录了,然后根据名称,一个一个下载就可以了。 --------------------编程问答--------------------
是的,获取目录,然后对记录下目录中的".txt"文件就可以了。
补充:.NET技术 , C#