我正试图用win表单将文件从我的电脑上传到远程服务器,但我收到了以下错误:登录失败:未知用户名或密码错误。在我的计算机上,我使用我的域用户并上传远程服务器的文件本地用户
我发现,我需要模拟我的用户,但我仍然不知道如何模拟NetworkCredential。
这是我的代码:
if (tbUsername.Text != string.Empty && tbPassword.Text != string.Empty && userSelectedFilePath != string.Empty)
{
try
{
using (WindowsIdentity.GetCurrent().Impersonate())
{
WebClient client = new WebClient();
NetworkCredential nc = new NetworkCredential("\\" + targetServer.Host + "\" + tbUsername.ToString(), tbPassword.ToString());
client.Credentials = nc;
client.UploadFile(targetServer, filepath);
MessageBox.Show("the file was successfully uploaded", "information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("One of the fields is empty", "Fields Empty", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
执行以下步骤:
打开"控制面板"
选择"管理工具"
打开"本地安全策略"
在左侧窗格中导航到"安全设置"=>"本地策略"=>"安全选项"
在右侧窗格中找到"网络访问:本地帐户的共享和安全模型"
双击以更改
将其设置为"Classic-Local users authenticate as self"
我已经重写了代码部分,现在它工作得很好。现在看起来是这样的:
IntPtr admin_token = default(IntPtr);
WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
WindowsIdentity wid_admin = null;
WindowsImpersonationContext wic = null;
if ((LogonUser(tbUsername.Text, targetServer.Host, tbPassword.Text, 9, 0, ref admin_token)) != 0 || (LogonUser(tbUsername2.Text, targetServer.Host, tbPassword2.Text, 9, 0, ref admin_token)) != 0)
{
wid_admin = new WindowsIdentity(admin_token);
wic = wid_admin.Impersonate();
}