Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 648
ro-E Avatar asked Dec 09 '25 21:12

ro-E


1 Answers

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:

  • Create a local empty temporary directory
  • Upload it using the Session.PutFiles, setting permissions you need in TransferOptions.FilePermissions
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.

like image 50
Martin Prikryl Avatar answered Dec 11 '25 10:12

Martin Prikryl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!