嗨,感谢您的期待!如何为给定FTP地址的所有文件提取文件位置(路径和文件名)?
背景
我需要拉所有文件的文件位置(路径和文件名)在给定的FTP地址。
对于映射的网络或本地驱动器上的文件,该代码将工作:
foreach(string fileName f in Directory.GetFiles("C\\:SomeDirectory"), "*.*",
SearchOption.AllDirectories)
{
//do stuff with each file found
}
但这不会工作在FTP连接。我已经找到this MS documentation,其中涵盖了建立一个FTPWebRequest,但它并没有告诉我如何遍历每个找到的文件(在所有的嵌套目录中)。
我在表单应用中使用C#。
问题
如何做到这一点:
foreach(string fileName f in Directory.GetFiles("C\\:SomeDirectory"), "*.*",
SearchOption.AllDirectories)
{
//do stuff with each file found
}
与FTP连接?
非常感谢!
更新/最终答案
特别感谢@sunk为了实现这一目标。我对他的代码做了一个小小的修改,使它完全递归,以便它可以钻入嵌套的文件夹。这里是最终代码:
//A list that holds all file locations in all folders of a given FTP address:
List<string> fnl= new List<string>();
//A string to hold the base FTP address:
string ftpBase = "ftp://[SOME FTP ADDRESS]";
//A button-click event. Can be a stand alone method as well
private void GetFileLocations(object sender, EventArgs e)
{
//Get the file names from the FTP location:
DownloadFileNames(ftpBase);
//Once 'DownloadFileNames' has run, we have populated 'fnl'
foreach(var f in fnl)
{
//do stuff
}
}
//Gets all files in a given FTP address. RECURSIVE METHOD:
public void DownloadFileNames(string ftpAddress)
{
string uri = ftpAddress;
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
reqFTP.Credentials = new NetworkCredential("pella", "PellaWA01!");
reqFTP.EnableSsl = false;
reqFTP.KeepAlive = false;
reqFTP.UseBinary = true;
reqFTP.UsePassive = true;
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
List<string> files = new List<string>();
StreamReader reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
files.Add(reader.ReadLine());
reader.Close();
responseStream.Dispose();
//Loop through the resulting file names.
foreach (var fileName in files)
{
var parentDirectory = "";
//If the filename has an extension, then it actually is
//a file and should be added to 'fnl'.
if (fileName.IndexOf(".") > 0)
{
fnl.Add(ftpAddress.Replace("ftp://pella.upload.akamai.com/140607/pella/", "http://media.pella.com/") + fileName);
}
else
{
//If the filename has no extension, then it is just a folder.
//Run this method again as a recursion of the original:
parentDirectory += fileName + "/";
try
{
DownloadFileNames(ftpAddress + parentDirectory);
}
catch (Exception)
{
//throw;
}
}
}
}
你已经采取了看的FtpWebRequest - http://msdn.microsoft.com/en-我们/图书馆/ system.net.ftpwebrequest.aspx – 2012-02-06 19:25:45
在我看来,你链接的例子给你你需要的一切。少了什么东西? – vlad 2012-02-06 19:27:52
@vlad OP想知道如何迭代返回的文件/目录(以及对它们做什么)。 – 2012-02-06 19:29:15