C# 如何获取FTP服务器上文件的最后修改日期
这是我的密码C# 如何获取FTP服务器上文件的最后修改日期,c#,.net,ftp,ftpwebrequest,C#,.net,Ftp,Ftpwebrequest,这是我的密码 FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(FTPAddress); ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails; FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse(); StreamReader streamReader = new Stream
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(FTPAddress);
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
List<string> directories = new List<string>();
string line = streamReader.ReadLine();
while (!string.IsNullOrEmpty(line))
{
directories.Add(line);
line = streamReader.ReadLine();
}
我的问题是如何从那一行中得到时间?我应该解析字符串吗?我不这么认为,因为我读到有LastModified
属性,但我不知道如何使用它
您能帮助我吗?尝试使用MS文档中的以下代码:
// Get the object used to communicate with the server.
Uri serverUri = new Uri("ftp://mypath/myfile.txt");
FtpWebRequest request = (FtpWebRequest)WebRequest.Create (serverUri);
request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
FtpWebResponse response = (FtpWebResponse)request.GetResponse ();
DateTime lastModifiedDate = response.LastModified;
您应该为每个文件执行此操作。
要做到这一点,也不简单。您必须解析目录列表响应的结果
看看这家伙是怎么做到的:
您应该能够对每一行进行foreach读取。不幸的是,使用.NET framework提供的功能检索目录中所有文件的修改时间戳没有真正可靠和有效的方法,因为它不支持FTP
MLSD
命令。MLSD
命令以标准化的机器可读格式提供远程目录列表。命令和格式由标准化
您可以使用.NET framework支持的备选方案:
方法(FTPListDirectoryDetails
命令)检索目录中所有文件的详细信息,然后处理FTP服务器特定格式的详细信息 DOS/Windows格式:LIST
*nix格式:
方法(FTPGetDateTimestamp
命令),分别检索每个文件的时间戳。一个优点是响应由toMDTM
标准化。缺点是您必须为每个文件发送单独的请求,这可能会非常低效。此方法使用您提到的:yyymmddhhmmss[.sss]
const string uri = "ftp://example.com/remote/path/file.txt"; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri); request.Method = WebRequestMethods.Ftp.GetDateTimestamp; FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Console.WriteLine("{0} {1}", uri, response.LastModified);
或者,您可以使用支持现代
MLSD
命令的第三方FTP客户端实现
例如,我们支持这一点
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = "example.com",
UserName = "username",
Password = "password",
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Get list of files in the directory
string remotePath = "/remote/path/";
RemoteDirectoryInfo directoryInfo = session.ListDirectory(remotePath);
foreach (RemoteFileInfo fileInfo in directoryInfo.Files)
{
Console.WriteLine("{0} {1}", fileInfo.Name, fileInfo.LastWriteTime);
}
}
(我是WinSCP的作者)这已经有几年历史了,但我想分享我的解决方案,因为我不得不这么做 我使用MSDN示例获取FTP目录列表: 这是正则表达式解析结果的答案(我实际上使用了Nyerguds的注释): 下面是我编写的一个简单类,用于“重新格式化”目录列表中的对象(目前它只处理顶级文件夹,但希望我可以在此处对其进行改进和更新:):
使用系统;
使用System.Collections.Generic;
利用制度全球化;
使用System.IO;
使用System.Linq;
Net系统;
使用System.Text.RegularExpressions;
名称空间FTPHelper
{
公共类FTPItem
{
public char[]权限{get;set;}
公共整数大小{get;set;}
公共日期时间LastModified{get;set;}
公共字符串名称{get;set;}
公共字符串完整路径{get;set;}
公共重写字符串ToString()
{
返回名称;
}
}
公共类ftp目录:FTPItem
{
公共FTPDirectory(){}
公共FTP目录(FTPItem项目)
{
权限=项。权限;
尺寸=项目尺寸;
LastModified=item.LastModified;
名称=项目名称;
FullPath=item.FullPath;
}
公共惰性子项{get;set;}
}
公共类FTPFile:FTPItem
{
公共FTPFile(){}
公共FTPFile(FTPItem项目)
{
权限=项。权限;
尺寸=项目尺寸;
LastModified=item.LastModified;
名称=项目名称;
FullPath=item.FullPath;
}
}
公共类FTP客户端
{
私有字符串地址;
私有字符串用户名;
私有字符串密码;
公共FTPClient(字符串地址、字符串用户名、字符串密码)
{
this.address=address.StartsWith(“ftp://”,StringComparison.OrdinalIgnoreCase)?地址:$“ftp://{address}”;
this.username=用户名;
this.password=密码;
}
公共列表检索DirectoryListingsFromFTP(字符串startingPath=null)
{
列表结果=新列表();
字符串路径=!string.IsNullOrEmpty(startingPath)?startingPath.Replace(“,“%20”):地址;
path=!path.StartsWith(address)?$“{address}/{path}”:path;
FtpWebRequest=(FtpWebRequest)WebRequest.Create(path);
request.Method=WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials=新的网络凭据(用户名、密码);
request.KeepAlive=false;
request.UseBinary=true;
request.usesponsive=true;
Regex directoryListingRegex=newregex(@“^([d-])((?:[rwxt-]{3}){3})\s+\d{1,}\s+.*(\d{1,})\s+(\w+)\s+(\d{1,2})\s+(\d{4})?(\d{1,2}:\d{2})?\s+(,
RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
使用(FtpWebResponse响应=(FtpWebResponse)request.GetResponse())
{
使用(Stream responseStream=response.GetResponseStream())
{
使用(StreamReader=新StreamReader(responseStream))
{
弦线;
而((line=reader.ReadLine())!=null)
{
Match Match=directoryListingRegex.Match(行);
FTPItem项目=新FTPItem
{
权限=匹配。组[2]。值。ToArray(),
Size=int.Parse(match.Groups[3].Value),
LastModified=DateTime.ParseExact($“{match.Groups[4]}{match.Groups[5]}{match.Groups[6]}{match.Groups[7]}”,
$“MMM dd{(match.Groups[6]。值!=”“?“yyyy”:”“)}{(match。