SSH.NET: 是否可以使用 SFTP 上传文件并保留源文件的文件日期?

SSH.NET: Is it possible to upload files using SFTP and preserve the file dates from source files?

目前,我正在使用 Renci SSH.NET 库通过 SFTP 将文件上传到 Unix 服务器。我不喜欢的一件事是上传文件后,创建日期和修改日期更改为上传发生的时间。

我想保留源文件中的原始文件日期,可以吗?

SSH.NET 库不会自动为您完成。您必须对其进行编码。

SftpClient.SetLastWriteTimeSftpClient.SetLastWriteTimeUtc两种方法。但实际上还没有实现。

您可以改为这样编码:

SftpFileAttributes fileAttributes = client.GetAttributes(targetFile);
fileAttributes.LastWriteTime = File.GetLastWriteTime(sourceFile);
client.SetAttributes(targetFile, fileAttributes);

尽管由于 SftpFileAttributes 中缺少 UTC API,如果客户端和服务器不在同一时区,您可能无法正确设置时间戳。


详情请看我的回答:


或者使用另一个能够自动保存时间戳的 SFTP 库,最好支持 UTC。

例如,WinSCP .NET assembly does it automatically. Just use the Session.PutFiles method:

session.PutFiles(sourceFile, targetFile).Check();

(我是WinSCP的作者)