Search code examples
c#directoryfile-permissionswinscpwinscp-net

How to set folder permissions after creating directory with WinSCP .NET assembly?


I'm building a web site and I want that when a user registers, to create a directory on the SFTP server and put in that directory a new file

I'm using WinSCP .NET assembly, and writing C#.

I noticed that you are able to set permissions only in the method: Session.PutFiles and not in the method: Session.CreateDirectory

Snd so after I create the directory and put the file in it, I cannot access the file because I don't have permissions - I'm accessing the file with the full URL

How can I access the file?

PS. When I change the directory permissions manually, I am able to access the file.


Solution

  • Note that this answers your question how to set permissions when creating a directory. But a root cause of your problem is that a default permissions your server sets are wrong. The server should not use default permissions such that you cannot access a directory/file you have just created yourself!

    It's currently not possible to directly set permissions, when a creating directory or modify them afterwards with WinSCP .NET assembly.
    See https://winscp.net/tracker/1075

    You can hack it though as follows:

    string directoryName = "mydir";
    string directoryPath = "/home/username/" + directoryName;
    string tempPath = Path.Combine(Path.GetTempPath(), directoryName);
    
    Directory.CreateDirectory(tempPath);
    
    try
    {
        TransferOptions options = new TransferOptions();
        options.FilePermissions = new FilePermissions { Octal = "755" };
        session.PutFiles(tempPath, directoryPath, false, options).Check();
    }
    finally
    {
        Directory.Delete(tempPath);
    }
    

    You can even do without creating an empty temporary directory. Just pick any directory, e.g. directory of your account profile folder, and use a file mask to include only this one directory, preventing files in the directory and sub-directories from being uploaded. Also use an explicit name of desired remote directory in the target path to "rename" the uploaded directory to the name you want.