Search code examples
directorydirectoryentry

Creating folders using DirectoryEntry


I am writing an ASP.NET (C#) application to create users for my domain. It also has to create folders and shares on a separate file server. I have so far been able to accomplish my task using

  • System.IO.Directory.CreateDirectory to create the folders,
  • a ("WinNT://fileserver/lanmanserver") DirectoryEntry to create the shares.

Unfortunately, my ASP.NET application has to run with impersonation on to create the folder. I don't like that. I would like to know if there is a way to create a folder on the file server using a DirectoryEntry object since i can pass the needed credentials to its constructor. Or, alternatively, is there a way to pass credentials to Directory.CreateDirectory?

Thanks in advance. Here is the current code, just in case

strPath = "\\myServer\D$\newDir";
Directory.CreateDirectory(strPath);

using (DirectoryEntry deFS = new DirectoryEntry("WinNT://myServer/lanmanserver"))
{
    using (DirectoryEntry deSH = deFS.Children.Add("newDir$", "fileshare"))
    {  
       deSH.Properties["path"].Value = "D:\\newDir";
       deSH.Properties["description"].Value = "My Stackoverflow sample share";
       deSH.CommitChanges();
    }
}

Solution

  • I don't believe you should be using DirectoryObject for that purpose, it wasn't made for such an access. But here's a trick you could be using to make impersonation easier. Create an impersonator class, which would implement IDisposable, something like this:

    public class Impersonator : IDisposable
    {
        public Impersonator(userid, password) 
        {
            ... LogonUserEx();
            ... DuplicateToken();
            ... Impersonate();
        }
        public void Dispose()
        {
            ... RevertToSelf();
        }
    }
    

    then you would be able to do this:

    using(new Impersonator("myaccount", "password"))
    {
         ... do stuff that requires impersonation
    }