jonas_adam
jonas_adam

Reputation: 31

How to create a folder with c# which is NOT read only?

In my C# forms application, I try to download the data in a directory of my SFTP Server. The data should be stored in a folder which I want to create in "MyDocuments". When the folder is created, I receive an Renci error "failure" because the folder is "read-only".

I tried many ways to create a folder, but I in most ways I used I either got an error, that I don't have the permission to create a folder, or I got an empty file instead of a folder. Right now I got a folder, but unluckily it is read only.

String localPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\MyNewFolder\\";

if (Directory.Exists(localPath))
{
    Console.WriteLine("Folder already exists");
}

if (!Directory.Exists(localPath))
{
    Directory.CreateDirectory(localPath);

    DirectoryInfo directory = new DirectoryInfo(localPath);
    DirectorySecurity security = directory.GetAccessControl();
}

I expect the folder not to be read only, so that I can safe data in it using my programm. Anyone knows why my code still creates a read only one?

Upvotes: 1

Views: 738

Answers (1)

Richard Stone
Richard Stone

Reputation: 23

I believe you have to set the following using the DirectorySecurity object:

        DirectorySecurity securityRules = new DirectorySecurity();
        securityRules.AddAccessRule(new FileSystemAccessRule(@"Domain\Account", FileSystemRights.FullControl, AccessControlType.Allow));

Then you can create the directory using the following:

DirectoryInfo di = Directory.CreateDirectory(@"directoryToCreatePath", securityRules);

EDITED:

Once you've created the directory using Directory.CreateDirectory(), you can then apply the following to the folder. This will allow the user you've specified to have FullControl of the folder. You can check the permissions for that user via Properties > Security

DirectoryInfo directory = new DirectoryInfo("C:\\CreatedFolder");

DirectorySecurity security = directory.GetAccessControl();

security.AddAccessRule(new FileSystemAccessRule(@"USERNAME",
                                FileSystemRights.FullControl,
                                AccessControlType.Allow));

directory.SetAccessControl(security);

Upvotes: 1

Related Questions