I have a Windows service developed in C # and .NET 3.5 to perform various administrative tasks on all our domains. I have an administrator account in each domain that has the necessary rights / permissions for what this service does.
For all AD interactions, I can bind to AD using the correct username / password for the domain, and all this is good. However, now I need to run an external process (robocopy) to do some work, and I cannot find code examples for this in .NET 3.5.
What I need to do is run robocopy using alternate credentials in a hidden window, grab the standard output so that I have a log of what was actually done, and grab the exit code so that I can see if it succeeded.
I found old .NET 1.1 code from K. Scott Allen (see the last few comments for good code) that extends the System.Diagnostics.Process object and calls the Win32 API function CreateProcessAsUserW. However, the code does not work due to some API changes in .NET 2.0. Using the code snippet from the last blog comment with a link where it uses reflection to call the private SetProcessHandle function of the Process object causes Access Denied errors when I try to interact with the process (to kill it or get the exit code).
Does anyone have a good example of how to do this?
EDIT: The integrated .NET Process interface and the ProcessStartInfo API allow you to specify alternate credentials, but when you do this, it wants to create a visible window (even if you specify CreateNoWindow or WindowStyle Hidden) that does not work when launched as a Windows Service. Therefore, this is not an option for this application. Impersonation does not work since when it starts the external process, it uses the credentials of the parent process, and not the credentials issued to it.
: , P/Invoke API Win32 . , NT4 RunProcess, / . Vista 2k3, Windows, Local System.