C# 选择文件并将其复制到远程位置的最佳做法?

C# 选择文件并将其复制到远程位置的最佳做法?,c#,C#,我有一个要求,当点击按钮时,应用程序连接到远程pc,用户可以浏览到c驱动器上的文件夹,然后将文件复制到他们的pc(不是在LAN上,而是远程位置) 使用远程桌面连接时,详细信息如下(例如): 计算机:abcd.dyndns.org:1234 用户名:bob2\apple 密码:密码 在做了一些研究之后,使用WMI或模拟似乎是最好的选择。这就是我使用模拟方法的地方 [DllImport("advapi32.DLL", SetLastError=true)] public static extern

我有一个要求,当点击按钮时,应用程序连接到远程pc,用户可以浏览到c驱动器上的文件夹,然后将文件复制到他们的pc(不是在LAN上,而是远程位置)

使用远程桌面连接时,详细信息如下(例如):

计算机:abcd.dyndns.org:1234
用户名:bob2\apple
密码:密码

在做了一些研究之后,使用WMI或模拟似乎是最好的选择。这就是我使用模拟方法的地方

[DllImport("advapi32.DLL", SetLastError=true)]
public static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType,
int dwLogonProvider, ref IntPtr phToken);

private void button4_Click(object sender, EventArgs e)
{
    WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
    WindowsImpersonationContext wic = null;
    try
    {
        IntPtr admin_token = new IntPtr();

        if (LogonUser("bob2\apple", "abcd.dyndns.org:1234","password",9, 0, ref admin_token) != 0)
        {   
            wic = new WindowsIdentity(admin_token).Impersonate();

            // NOT SURE ABOUT THIS BIT.....
            File.Copy(@"", @"", true);
            MessageBox.Show("Copy Succeeded");
        }
        else
        {
            MessageBox.Show("Copy Failed");
        }
    }
    catch(Exception se)
    {
        int ret = Marshal.GetLastWin32Error();
        MessageBox.Show(ret.ToString(), "Error code: " + ret.ToString());
        MessageBox.Show(se.Message);
    }
    finally
    {
        if (wic != null)
        wic.Undo();
    }           
}

模拟用户执行的操作需要包含在Using语句中

按照LogonUser说明,尝试以下操作:

using (wic = WindowsIdentity.Impersonate(admin_token))
{
        // these operations are executed as impersonated user

        File.Copy(@"", @"", true);
        MessageBox.Show("Copy Succeeded");
}

另请参见“WindowsIdentity.Impersonate方法”MSDN页面:

那么,您的问题是什么?