C# LogonUser函数在c中失败,错误代码为0#
我的目标是将文件夹从我的系统复制到c#中的远程计算机。 我到处搜索,找到了一些关于如何做到这一点的信息。我使用域、用户名和密码调用LogonUser函数,但它失败并返回0 下面是我的一段代码。你能帮我解决这个问题吗C# LogonUser函数在c中失败,错误代码为0#,c#,.net,windows-identity,impersonation,C#,.net,Windows Identity,Impersonation,我的目标是将文件夹从我的系统复制到c#中的远程计算机。 我到处搜索,找到了一些关于如何做到这一点的信息。我使用域、用户名和密码调用LogonUser函数,但它失败并返回0 下面是我的一段代码。你能帮我解决这个问题吗 class Program { #region Assembly Functions [DllImport("advapi32.dll")] public static extern bool LogonUser(string lpszUsername, st
class Program
{
#region Assembly Functions
[DllImport("advapi32.dll")]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword,
int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
[DllImport("kernel32.dll")]
public static extern bool CloseHandle(IntPtr handle);
#endregion
static void Main(string[] args)
{
SafeTokenHandle safeTokenHandle;
WindowsImpersonationContext impersonatedUser = null;
WindowsIdentity newId;
IntPtr tokenHandle;
IntPtr userHandle = IntPtr.Zero;
tokenHandle = IntPtr.Zero;
Console.WriteLine("Enter your domain.");
string domain = Console.ReadLine();
Console.WriteLine("Enter you user name.");
string uname = Console.ReadLine();
Console.WriteLine("Enter your password (Caution, password won't be hidden).");
string password = Console.ReadLine();
const int LOGON32_PROVIDER_DEFAULT = 0;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
bool logon = LogonUser(uname, domain, password,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);
if (false == logon)
{
int ret = Marshal.GetLastWin32Error();
Console.WriteLine("LogonUser failed with error code : {0}", ret);
throw new System.ComponentModel.Win32Exception(ret);
}
if (logon)
{
newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
using (impersonatedUser = newId.Impersonate())
{
// Check the identity.
Console.WriteLine("After impersonation: "
+ WindowsIdentity.GetCurrent().Name);
}
File.Copy(@"c:\result.xml", @"C:\result.xml", true);
}
//Undo impersonation
if (impersonatedUser != null)
{
impersonatedUser.Undo();
}
if (tokenHandle != IntPtr.Zero)
{
CloseHandle(tokenHandle);
}
}
}
public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeTokenHandle()
: base(true)
{
}
[DllImport("kernel32.dll")]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr handle);
protected override bool ReleaseHandle()
{
return CloseHandle(handle);
}
}
为什么不使用“Windows API代码包1.1”来演示(除其他外)如何使用shell进行拖放操作?这是您基本上尝试的操作
如果使用Shell,您不必考虑如何登录以及支持各种情况所需的1000件其他事情
下载“Windows API代码包1.1”包,并查找DragAndDropWindow示例或其他一些示例。您好,LastError 0表示成功-。我认为这种情况下的问题是被阻止的帐户、错误的密码或类似的事情,但代码应该是可以的。您应该使用
[DllImport(“advapi32.dll”,SetLastError=true)]
来获得封送。GetLastWin32Error
正常工作。默认情况下,SetLastError
为false。因此,请更新您的代码,并让我们知道结果。