1

I am trying to write code to programmatically create a directory (and do other file manipulations) on a server from an application on my workstation -- using Directory.CreateDirectory this would be easy enough, and I know how to do that. HOWEVER, the problem is that I am trying to do this on a server where my user id doesn't have rights to do so. I do have an A/D user id to do it with, but I am clueless as to how to use it in my application to do what I need to do (impersonation isn't what it's called, but...).

Here's what I am trying to do:

System.Security.AccessControl.DirectorySecurity ds = new System.Security.AccessControl.DirectorySecurity();

// <-- something magic happens here -->

Directory.CreateDirectory(@"\\ofmsws42\c$\New_Directory", ds);

What goes into the spot where the "magic" happens? Or am I barking up the wrong tree? I want to say that my credentials for the server end up somewhere in the DirectorySecurity object I am creating, but none of the properties of DirectorySecurity appear to do the trick.

Cyberherbalist
  • 12,061
  • 17
  • 83
  • 121

1 Answers1

3

You need to impersonate with the account that have permissions in "magic code".

WindowsIdentity.Impersonate have sample (referenced from SO: How do you do Impersonation in .NET?)

Here are most important chunks of code (LogonUser is PInvoke from advapi32.dll):

// Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser(userName, domainName, Console.ReadLine(),
      LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
      out safeTokenHandle);

using (WindowsImpersonationContext impersonatedUser = 
   WindowsIdentity.Impersonate(safeTokenHandle.DangerousGetHandle()))
{
...
}
Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179