如何将凭据传递给计算机,以便我可以使用Microsoft.Win32.RegistryKey.OpenRemoteBaseKey()?

时间:2010-03-29 21:46:47

标签: c# .net registry credentials remote-access

This .NET API如果我正在尝试在与我相同的域中的机器中打开注册表(并且我的登录用户在目标计算机上具有管理员权限),则可以正常工作。

如果它是一个具有不同的本地管理用户(我有密码)的域外机器,那就太棘手了。

在调用OpenRemoteBaseKey()之前,我尝试使用WNetUseConnection()(过去在我想要读取远程磁盘文件的情况下很好地帮助了我),但没有骰子 - 我得到了一个访问被拒绝的例外。

显然,我必须以其他方式传递证书,但是如何?

1 个答案:

答案 0 :(得分:32)

我成功用于访问计算机上的文件的代码如下:

    #region imports 
        [DllImport("advapi32.dll", SetLastError = true)] 
        private static extern bool LogonUser(string 
        lpszUsername, string lpszDomain, string lpszPassword, 
        int dwLogonType, int dwLogonProvider, ref 
IntPtr phToken); 


        [DllImport("kernel32.dll", CharSet = CharSet.Auto, 
        SetLastError = true)] 
        private static extern bool CloseHandle(IntPtr handle 
        ); 

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, 
        SetLastError = true)] 
        public extern static bool DuplicateToken(IntPtr 
        existingTokenHandle, 
        int SECURITY_IMPERSONATION_LEVEL, ref IntPtr 
        duplicateTokenHandle); 
        #endregion 
        #region logon consts 
        // logon types 
        const int LOGON32_LOGON_INTERACTIVE = 2; 
        const int LOGON32_LOGON_NETWORK = 3; 
        const int LOGON32_LOGON_NEW_CREDENTIALS = 9; 

        // logon providers 
        const int LOGON32_PROVIDER_DEFAULT = 0; 
        const int LOGON32_PROVIDER_WINNT50 = 3; 
        const int LOGON32_PROVIDER_WINNT40 = 2; 
        const int LOGON32_PROVIDER_WINNT35 = 1; 
        #endregion 

然后签署部分内容,只需使用:

        IntPtr token = IntPtr.Zero; 

        bool isSuccess = LogonUser("username", "domain", "password", 
        LOGON32_LOGON_NEW_CREDENTIALS, 
        LOGON32_PROVIDER_DEFAULT, ref token); 
        using (WindowsImpersonationContext person = new WindowsIdentity(token).Impersonate()) 
        { 
        //do your thing 
         person.Undo(); 
        } 

正如您可能看到的,“撤消()”将使您不再以该用户身份登录。所以在完成之前不要使用它。但别忘了使用它!

相关问题