c# - 当子目录不存在时,将文件上传到具有特定名称的子目录?

标签 c# file-permissions winscp winscp-net

也许这是一个由四部分组成的问题:

  1. 上传到子目录/ies
  2. 子目录不存在
  3. 使用与本地文件不同的远程文件名
  4. 子目录应该有明确的权限(类似于 WinSCP .NET assembly - How to set folder permissions after creating directory? 中的根问题)

尝试:

var localPath = Path.GetTempFileName();
var remoteFolder = "/some/directory/beneath/root";
var slash = "/"; // maybe given as '/' or '\'...
var remotePath = remoteFolder + slash + "destination.ext1.ext2.txt";
var session = new Session(sessionOptions);
var result = session.PutFiles(localPath, remotePath, false, new FileTransferOptions { FilePermissions = new FilePermissions { Octal = "700" }, KeepTimestamp..., etc });
result.Check();

抛出异常 无法创建远程文件“/some/directory/beneath/root/destination.ext1.ext2.txt”。 ---> WinSCP.SessionRemoteException: 没有那个文件或目录。

我终于能够通过 the crazy workaround indicated here 创建具有正确权限的子目录通过在我的临时路径中创建子目录结构并在 第一个文件夹 上使用 PutFiles:

var tempRoot = Path.GetTempPath();
var tempPath = Path.Combine(tempRoot, remoteFolder);
Directory.CreateDirectory(tempPath);

// only need to upload the first segment, PutFiles will magically grab the subfolders too...
var segment = remoteFolder.Substring(0, remoteFolder.IndexOf(slash, StringComparison.Ordinal));
if( !this.DoesFolderExist(segment) )
{
        // here's the workaround...
        try
        {
            this._session.PutFiles(Path.Combine(tempRoot, segment), segment, false, new TransferOptions { FilePermissions = this._transferOptions.FilePermissions }).Check();
        }
        catch (InvalidOperationException)
        {
            // workaround for bug in .NET assembly prior to 5.5.5/5.6.1 beta
            // although I never hit this catch, maybe I've got a new enough version?
        }
}
Directory.Delete(tempPath); // finish workaround

但这太不直观了。

最佳答案

ad 1) WinSCP 不会(通常)创建上传的目标目录。它必须在上传之前存在。您可以使用 Session.FileExists 测试是否存在并使用 Session.CreateDirectory 创建目录, 如果不。当然,如果需要,WinSCP 会创建您正在上传的目录。

广告 3) 您在 Session.PutFilesremotePath 参数中指定了不同的目标名称:

session.PutFiles(@"C:\path\original.txt", "/home/user/newname.txt");

广告 4) 您使用 TransferOptions.FilePermissions 指定上传文件/目录的权限.请注意,WinSCP 隐式地为每个组的目录添加了 x 权限,其中授予了 r 权限。所以当你指定600权限进行批量上传时,600用于文件,而700用于目录。如果需要对不同的文件/目录使用不同的权限,需要一个一个上传。

关于c# - 当子目录不存在时,将文件上传到具有特定名称的子目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25981730/

相关文章:

powershell - 使用PowerShell的WinSCP会将目录添加到我要上传到的SFTP站点

c# - 有没有办法在 C# 中创建一个 sqllocaldb 实例?

c# - 使用 ValueInjecter,我可以注入(inject)私有(private)属性吗?

c# - 在 Unity 中使用 getComponent 从附加到游戏对象的脚本中获取图像

windows - Windows 上的 Git 文件权限

.net - WinSCP .NET 程序集 - 记录期间发生错误。已关闭

c# - 需要有关 ASP.NET MVC 3 体系结构的一些指导

c - 从内核空间的文件指针获取fd

Python CGI 权限错误

winscp - 不要使用 WinSCP .NET 程序集遍历目录