.NET FTP 上传文件并保留原始日期时间

.NET FTP Upload file and preserve original date time

我们有一个 Windows 2008 R2 Web 服务器 FTP 通过 SSL。此应用程序使用 .NET 4.5,当我上传文件时,文件上的 date/time 更改为服务器上的当前 date/time。有没有办法让上传的文件保留原始(最后修改)日期?

这是我的:

FtpWebRequest clsRequest = (FtpWebRequest)WebRequest.Create(FTPFilePath);
clsRequest.EnableSsl = true;
clsRequest.UsePassive = true;
clsRequest.Credentials = new NetworkCredential(swwwFTPUser, swwwFTPPassword);
clsRequest.Method = WebRequestMethods.Ftp.UploadFile;
Byte[] bFile = File.ReadAllBytes(LocalFilePath);
Stream clsStream = clsRequest.GetRequestStream();
clsStream.Write(bFile, 0, bFile.Length);
clsStream.Close();
clsStream.Dispose();
clsRequest = null;

我知道我们可以分配文件属性:-

//Change the file created time.
File.SetCreationTime(path, dtCreation);
//Change the file modified time.
File.SetLastWriteTime(path, dtModified);

如果您可以在将原始日期保存到服务器之前提取原始日期,那么您就可以更改文件属性....像这样:-

Sftp sftp = new Sftp();
sftp.Connect(...);
sftp.Login(...);

// upload the file
sftp.PutFile(localFile, remoteFile);

// assign creation and modification time attributes
SftpAttributes attributes = new SftpAttributes();
System.IO.FileInfo info = new System.IO.FileInfo(localFile);
attributes.Created = info.CreationTime;
attributes.Modified = info.LastWriteTime;

// set attributes of the uploaded file
sftp.SetAttributes(remoteFile, attributes);

我希望这能为您指明正确的方向。

确实没有通过 FTP 协议更新远程文件时间戳的标准方法。这可能就是 FtpWebRequest 不支持它的原因。

有两种 non-standard 更新时间戳的方法。 non-standard MFMT 命令:

MFMT yyyymmddhhmmss path

或 non-standard 使用(否则为标准)MDTM 命令:

MDTM yyyymmddhhmmss path

但是 FtpWebRequest 也不允许您发送自定义命令。

参见示例 How to send arbitrary FTP commands in C#


所以你必须使用第 3 方 FTP 库。

例如WinSCP .NET assembly默认保留上传文件的时间戳。

// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Ftp,
    HostName = "example.com",
    UserName = "user",
    Password = "mypassword",
};

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    // Upload
    session.PutFiles(@"c:\toupload\file.txt*", "/home/user/").Check();
}

参见 a full example

请注意,WinSCP .NET 程序集不是本机 .NET 程序集。它是控制台应用程序周围的薄 .NET 包装器。

(我是WinSCP的作者)

这是一个较旧的问题,但我将在此处添加我的解决方案。我使用了一种类似于@Martin Prikryl 提出的解决方案的方法,使用 MDTM 命令。他的回答显示 DateTime 格式字符串为 yyyymmddhhmmss 这是不正确的,因为它没有正确处理月份和 24 小时时间格式。在这个答案中,我更正了这个问题并提供了一个使用 C# 的完整解决方案。

我使用了 FluentFTP 库,它可以很好地处理通过 C# 使用 FTP 的许多其他方面。要设置修改时间,这个库不支持它,但它有一个 Execute 方法。使用FTP命令MDTM yyyyMMddHHmmss /path/to/file.txt会设置文件的修改时间

注意:在我的例子中,我需要使用世界时,你可能就是这种情况。

下面的代码显示了如何连接到 FTP 并使用 Execute 方法设置最后修改时间并发送 MDTM 命令。

FtpClient client = new FtpClient("ftp-address", "username", "password");
client.Connect();

FtpReply reply = client.Execute($"MDTM {DateTime.UtcNow.ToString("yyyyMMddHHmmss")} /path/to/file.txt");