Question

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();
    }
}
Was it helpful?

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
}

OTHER TIPS

As far as I know you have two options: impersonate a user that has permissions to create the directory on the remote share or give the permissions to the default user that runs asp.net services.

What is wrong with that? You are accessing a non-default resource on your network and the default privileges dont allow you to do that. It's pretty much like a regular user account trying to write on a network share.

The DirectoryEntry class has a constructor which take username and password as input. Have you tried this?

See documentation at Microsoft

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top