问题:我想根据某些特定的dateTime从FTP服务器中获取文件详细信息,而无需使用任何第三方。
问题:我的FTP服务器包含1000个文件,因此获取所有文件,然后过滤后需要时间。
是否有更快的方法?
string ftpPath = "ftp://directory/";
// Some expression to match against the files...do they have a consistent
// name? This example would find XML files that had 'some_string' in the file
Regex matchExpression = new Regex("^test.+.xml$", RegexOptions.IgnoreCase);
// DateFilter
DateTime cutOff = DateTime.Now.AddDays(-10);
List<ftplineresult> results = FTPHelper.GetFilesListSortedByDate(ftpPath, matchExpression, cutOff);
public static List<FTPLineResult> GetFilesListSortedByDate(string ftpPath, Regex nameRegex, DateTime cutoff)
{
List<FTPLineResult> output = new List<FTPLineResult>();
FtpWebRequest request = FtpWebRequest.Create(ftpPath) as FtpWebRequest;
ConfigureProxy(request);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
FtpWebResponse response = request.GetResponse() as FtpWebResponse;
StreamReader directoryReader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.ASCII);
var parser = new FTPLineParser();
while (!directoryReader.EndOfStream)
{
var result = parser.Parse(directoryReader.ReadLine());
if (!result.IsDirectory && result.DateTime > cutoff && nameRegex.IsMatch(result.Name))
{
output.Add(result);
}
}
// need to ensure the files are sorted in ascending date order
output.Sort(
new Comparison<FTPLineResult>(
delegate(FTPLineResult res1, FTPLineResult res2)
{
return res1.DateTime.CompareTo(res2.DateTime);
}
)
);
return output;
}
问题:我的FTP服务器包含1000个文件,因此获取所有文件,然后过滤后需要时间。
有什么更快的方法吗?
否。
唯一的标准FTP API是LIST
命令及其同伴。所有这些都将为您提供文件夹中所有文件的列表。没有FTP API可以为您提供时间戳过滤的文件。
某些服务器支持 non-standard LIST
命令中的文件掩码。
因此,他们将允许您仅返回*.xml
文件。
查看如何使用FTP根据模式匹配获取文件列表?
类似的问题:
- 如果文件是在最后一个小时内创建的 ,则从FTP下载文件
- C# - 从FTP下载文件,该文件具有更高的最后修饰日期
我有一个替代解决方案可以使用FluentFTP进行我的功能。
说明:
我正在使用相同的文件夹结构从FTP(读取权限reqd。)下载文件。
因此,每当工作/服务运行时,我都可以检查到物理路径相同的文件(完整路径)是否存在,是否存在,则可以将其视为新文件。ii也可以采取一些行动并下载。
它只是一种替代解决方案。
代码更改:
private static void GetFiles()
{
using (FtpClient conn = new FtpClient())
{
string ftpPath = "ftp://myftp/";
string downloadFileName = @"C:tempFTPTest";
downloadFileName += "\";
conn.Host = ftpPath;
//conn.Credentials = new NetworkCredential("ftptest", "ftptest");
conn.Connect();
//Get all directories
foreach (FtpListItem item in conn.GetListing(conn.GetWorkingDirectory(),
FtpListOption.Modify | FtpListOption.Recursive))
{
// if this is a file
if (item.Type == FtpFileSystemObjectType.File)
{
string localFilePath = downloadFileName + item.FullName;
//Only newly created files will be downloaded.
if (!File.Exists(localFilePath))
{
conn.DownloadFile(localFilePath, item.FullName);
//Do any action here.
Console.WriteLine(item.FullName);
}
}
}
}
}