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.
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 (
LogonUseris PInvoke from advapi32.dll):