0

I am writing a program which create some share folders on a 2012 server. I have a service account :

NTAccount serviceAccount = new NTAccount("myDomain", "SA_LiPAM");

This initialization work well.

if (folder.IndexOf('\\') == 0)
{
    Directory.CreateDirectory("\\\\" + serveurName + "\\Test-Projects\\" + pPrjName.Text + folder);// Creation
    fs = Directory.GetAccessControl("\\\\" + serveurName + "\\Test-Projects\\" + pPrjName.Text + folder);
    fs.SetOwner(serviceAccount);// Set owner
    Directory.SetAccessControl("\\\\" + serveurName + "\\Test-Projects\\" + pPrjName.Text + folde, fs);
}

On execution evrything seems ok, but, when I look on Security>advanced of the folder the owner is the localadmin...

Which way to definetly change the owner of this folder ?

Edit : I was using "File" instead of "Directory" thats why it doesn't work.

Baptiste
  • 121
  • 2
  • 16
  • Create a new network connection with the credentials of the service account. Here is an example https://gist.github.com/AlanBarber/92db36339a129b94b7dd – Ben Jul 20 '17 at 13:27
  • Why did I have to do that ? the server don't recognize the service account before ? – Baptiste Jul 20 '17 at 13:58
  • Is your program running under the service account? – Ben Jul 20 '17 at 14:10
  • No, the program use the current user identity the service account is used to manage the AD (creating some groups...) and to manage access right on the share. – Baptiste Jul 20 '17 at 14:14
  • Why are you using `File.GetAccessControl` instead of `Directory.GetAccessControl`? https://msdn.microsoft.com/en-us/library/c1f66bc2(v=vs.110).aspx – Ben Jul 20 '17 at 14:22
  • Ow, this is an error, I change it to Directory.GetAccessControl but not working same way no error on execution but the localadmin is the owner. EDIT : the owner of the root folder don't change evrytime I work on "+ folder" bug is fixed with "Directory.GetAccessControl" :) – Baptiste Jul 20 '17 at 14:27
  • Please update your question with the right code – Ben Jul 20 '17 at 14:30

1 Answers1

0

Please try the following code. I have used this link C# - How to use DirectorySecurity.SetOwner() ? I'm having troubles to create it

if (folder.IndexOf('\\') == 0)
{
    string dir = "\\\\" + serveurName + "\\Test-Projects\\" + pPrjName.Text + folder;
    Directory.CreateDirectory(dir);                    
    DirectoryInfo di = new DirectoryInfo(dir);
    DirectorySecurity ds = di.GetAccessControl();                    
    ds.SetOwner(serviceAccount);
    FileSystemAccessRule permissions = new FileSystemAccessRule(serviceAccount, FileSystemRights.FullControl, AccessControlType.Allow);
    ds.AddAccessRule(permissions);
    di.SetAccessControl(ds);
}
Ben
  • 763
  • 1
  • 5
  • 14