How to specify the user in a C# Thread
how can I spawn the thread T from application A so that that application A's user is U1 (like me) but thread T's user is U2 (like a superuse开发者_JAVA百科r)?
Thanks
Have a look at the example code for the property Thread.CurrentPrincipal:
http://msdn.microsoft.com/en-us/library/system.threading.thread.currentprincipal.aspx
You'll need to call WindowsIdentity.Impersonate() on the thread. It is one of the very few .NET class methods where you have to use P/Invoke, LogonUser() is necessary to get the impersonation token. It is well described in the code example shown in the linked MSDN article.
While not directly a duplicate, I think this question may be what you want. On the other hand, do you need to launch an impersonated thread? I don't know how well that plays with UAC (User Account Control). From that point of view, UAC COM elevation may be an interesting read as well, since you can create a COM object elevated, and you can write a COM object in .NET.
If what you actually want is to execute some code as administrator, you'll want to go with the second approach and let User Account Control handle the rest. Makes it easy for Vista and 7 (and the future), though running on XP may make things more complicated (or require running the entire application as administrator).
精彩评论