[本文轉自博客堂] 在Windows Vista运行Visual Studio 2005(without SP1)时,最好使用Vista的Run as administrator的功能,否则有些功能就不能正常工作。而在我们开发的.NET程序内部,有时也会碰到需要临时提高权限的情形。ASP.NET程序员经常问的一个问题是,我的代码为什么没有权限创建一个文件?基本的解决方案有三个:
1namespace Sunmast.SharedCode 2{ 3/**////<summary> 4/// The type of logon operation to perform. 5///</summary> 6enum LogonType : uint 7{ 8/**////<summary> 9/// This logon type is intended for users who will be interactively using the computer, such as a user being logged on by a terminal server, remote shell, or similar process. This logon type has the additional expense of caching logon information for disconnected operations; therefore, it is inappropriate for some client/server applications, such as a mail server. 10///</summary> 11 Interactive =2, 12/**////<summary> 13/// This logon type is intended for high performance servers to authenticate plaintext passwords. The LogonUser function does not cache credentials for this logon type. 14///</summary> 15 Network =3, 16/**////<summary> 17/// This logon type is intended for batch servers, where processes may be executing on behalf of a user without their direct intervention. This type is also for higher performance servers that process many plaintext authentication attempts at a time, such as mail or Web servers. The LogonUser function does not cache credentials for this logon type. 18///</summary> 19 Batch =4, 20/**////<summary> 21/// Indicates a service-type logon. The account provided must have the service privilege enabled. 22///</summary> 23 Service =5, 24/**////<summary> 25/// This logon type is for GINA DLLs that log on users who will be interactively using the computer. This logon type can generate a unique audit record that shows when the workstation was unlocked. 26///</summary> 27 Unlock =7, 28/**////<summary> 29/// This logon type preserves the name and password in the authentication package, which allows the server to make connections to other network servers while impersonating the client. A server can accept plaintext credentials from a client, call LogonUser, verify that the user can access the system across the network, and still communicate with other servers. 30///</summary> 31 NetworkClearText =8, 32/**////<summary> 33/// This logon type allows the caller to clone its current token and specify new credentials for outbound connections. The new logon session has the same local identifier but uses different credentials for other network connections.<br/> 34/// This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider. 35///</summary> 36 NewCredentials =9 37 } 38 39/**////<summary> 40/// Specifies the logon provider. 41///</summary> 42enum LogonProvider : uint 43{ 44/**////<summary> 45/// Use the standard logon provider for the system.<br/> 46/// The default security provider is negotiate, unless you pass NULL for the domain name and the user name is not in UPN format. In this case, the default provider is NTLM. 47///</summary> 48 Default =0, 49/**////<summary> 50/// Use the Windows NT 3.5 logon provider. 51///</summary> 52 WinNT35 =1, 53/**////<summary> 54/// Use the NTLM logon provider. 55///</summary> 56 WinNT40 =2, 57/**////<summary> 58/// Use the negotiate logon provider. 59///</summary> 60 WinNT50 =3, 61 } 62 63/**////<summary> 64/// Use identity scope to impersonate a different user 65///</summary> 66class IdentityScope : IDisposable 67{ 68 [DllImport("Advapi32.dll")] 69staticexternbool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, 70 LogonType dwLogonType, LogonProvider dwLogonProvider, out IntPtr phToken); 71 [DllImport("Advapi32.DLL")] 72staticexternbool ImpersonateLoggedOnUser(IntPtr hToken); 73 [DllImport("Advapi32.DLL")] 74staticexternbool RevertToSelf(); 75 [DllImport("Kernel32.dll")] 76staticexternint GetLastError(); 77 78bool disposed; 79 80public IdentityScope(string domain, string userName, string password) 81 : this(domain, userName, password, LogonType.Interactive, LogonProvider.Default) 82{ 83 } 84 85public IdentityScope(string domain, string userName, string password, LogonType logonType, LogonProvider logonProvider) 86{ 87if (string.IsNullOrEmpty(userName)) 88{ 89thrownew ArgumentNullException("userName"); 90 } 91if (string.IsNullOrEmpty(domain)) 92{ 93 domain ="."; 94 } 95 96 IntPtr token; 97int errorCode =0; 98if (LogonUser(userName, domain, password, logonType, logonProvider, out token)) 99{ 100if (!ImpersonateLoggedOnUser(token)) 101{ 102 errorCode = GetLastError(); 103 } 104 } 105else 106{ 107 errorCode = GetLastError(); 108 } 109if (errorCode !=0) 110{ 111thrownew Win32Exception(errorCode); 112 } 113 } 114 115~IdentityScope() 116{ 117 Dispose(false); 118 } 119 120protectedvirtualvoid Dispose(bool disposing) 121{ 122if (!disposed) 123{ 124if (disposing) 125{ 126// Nothing to do. 127 } 128 RevertToSelf(); 129 disposed =true; 130 } 131 } 132 133publicvoid Dispose() 134{ 135 Dispose(true); 136 GC.SuppressFinalize(this); 137 } 138 } 139}