C# 如何在Windows计算机上以编程方式登录
可以使用logonuser函数登录到域 我想通过编程方式从C#登录到不属于任何域的windows计算机上。如何做到这一点 我正在使用以下程序登录:C# 如何在Windows计算机上以编程方式登录,c#,windows,winapi,authentication,C#,Windows,Winapi,Authentication,可以使用logonuser函数登录到域 我想通过编程方式从C#登录到不属于任何域的windows计算机上。如何做到这一点 我正在使用以下程序登录: [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool LogonUser(String lpszUsername, String lpszDomain, String
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
internal void validateusercredentials(string username, string password, string hostname)
{
assert.isnotnull(username);
intptr tokenhandle = new intptr(0);
windowsidentity windowsid = null;
try
{
const int logon32_provider_default = 0;
const int logon32_logon_network = 3;
tokenhandle = intptr.zero;
bool success = logonuser(username, ".", password, logon32_logon_network,
logon32_provider_default, ref tokenhandle);
console.writeline("the return value of logon user is " + success);
if (!success)
{
int lastwindowserror = marshal.getlastwin32error();
if (lastwindowserror == error_logon_failure)
{
string message = string.format("invalid credentials supplied for user {0}", username);
console.writeline(lastwindowserror);
throw new invalidcredentialexception(message);
}
}
}
catch (exception e)
{
console.writeline(e.message);
trace.traceerror(e.message);
throw;
}
finally
{
if (tokenhandle != intptr.zero)
{
closehandle(tokenhandle);
}
if (windowsid != null)
{
windowsid.dispose();
windowsid = null;
}
}
}
如果计算机不是域的一部分,则无法使用域凭据
如果您有本地帐户,您可以改为使用计算机的本地名称作为域名,使用您的本地用户和密码作为用户和密码。LogonUser(用户名、主机名、密码、LOGON32\u登录\u网络、LOGON32\u提供程序\u默认值、参考令牌句柄);我将此与正确的凭据和域名绑定为windows计算机的名称。但它仍然没有登录。使用“.”表示本地身份验证。如果仍然失败,请添加GetLastError的详细信息您是真的要登录到域帐户还是本地帐户?我尝试登录到本地帐户您需要向我们显示您尝试使用的代码并提供出错的详细信息。LogonUser(用户名、主机名、密码、LOGON32\u登录\u网络、LOGON32\u提供程序\u默认值、ref tokenHandle)。这就是我试过的。主机名的值是完整的机器名。返回什么错误代码?