Search code examples
c#directoryiopermissionsimpersonation

creating (home) folder and setting folder permissions with other user impersonation in c#


Issue description

I am trying to create Active directory Users with my Program. All active directory related parts are working. What proves an Issue for me is the impersonation to create a folder on our file server and set the apropriate permissions. The issue with the impersonation is that multiple administrative accounts need to be used by the software. Hence it is not a solution to shift + rightclick -> run as different user

Task approach

So how I would handle it normally would include the following steps:

  1. Log in with an account with apropriate permissions on the home drive folder
  2. Navigate to '\FileServer\Data\Home'
  3. Create a folder for the user like '\FileServer\Data\Home\exampleuser1'
  4. Set the apropriate read/write permissions for that given user

Programmatically I would do something in the lines of (pseudocode):

string path = "\\FileServer\Data\Home\exampleuser1"
if (!Directory.Exists(path))
{
    Directory.Create(path);
    AddDirectorySecurity(path, @"MYDOMAIN\exampleuser1", FileSystemRights.TakeOwnership, AccessControlType.Allow);
}

however, this code would have to be executed with another user account "domain\admin_julian"


Solution

  • answer has been found here: How to provide user name and password when connecting to a network share (answer from Luke Quinane)

    implement his class and then use it like:

    using (new NetworkConnection(@"\\server\Data\Home", cred))
    {
        string path = $@"\\server\Data\Home\testuserfolder";
        string domainName = "domain.com";
        string userNameToCreate = "testuser";
        Directory.CreateDirectory(path);
        SetFullPermission(path, userNameToCreate);
    }