Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用UNC和模拟复制文件_C#_.net_File Copying - Fatal编程技术网

C# 使用UNC和模拟复制文件

C# 使用UNC和模拟复制文件,c#,.net,file-copying,C#,.net,File Copying,我想使用FileInfo和CopyTo在网络上移动一些文件。我必须将文件移动到必须使用特定用户帐户访问的服务器上的共享。我如何做到这一点-我必须模拟该用户,然后进行复制吗 我正在使用.NET4,想知道完成模拟的最佳方法是什么。我读过关于使用pInvoke和advapi32.dll的文章,但我希望有人能推荐一种更好的方法 谢谢你的想法 编辑 谢谢你的回复。这不是一个服务,它是一个控制台应用程序,但它将从多台机器上运行。使用映射比使用模拟有什么好处吗?反之亦然?推荐的方法是什么? 我也考虑过使用批处

我想使用FileInfo和CopyTo在网络上移动一些文件。我必须将文件移动到必须使用特定用户帐户访问的服务器上的共享。我如何做到这一点-我必须模拟该用户,然后进行复制吗

我正在使用.NET4,想知道完成模拟的最佳方法是什么。我读过关于使用pInvoke和advapi32.dll的文章,但我希望有人能推荐一种更好的方法

谢谢你的想法

编辑 谢谢你的回复。这不是一个服务,它是一个控制台应用程序,但它将从多台机器上运行。使用映射比使用模拟有什么好处吗?反之亦然?推荐的方法是什么?
我也考虑过使用批处理文件来创建映射并进行复制,但我不确定这有多容易完成,因为要从中复制的文件夹并不总是相同的-它总是在一个目录中,但是子目录名称会更改。

您不需要模拟,只需使用要使用的凭据建立文件映射即可。您可以使用shell out命令或

来完成此操作。如果您作为服务运行,则可能需要模拟。这不是完整的代码,而是其要点:

     [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)]
    private static extern unsafe int FormatMessage(int dwFlags, ref IntPtr lpSource, int dwMessageId, int dwLanguageId, ref string lpBuffer, int nSize, IntPtr* arguments);

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


IntPtr token = IntPtr.Zero;

            bool isSuccess = LogonUser(username, domain, password, impersonationType, Logon32ProviderDefault, ref token);
            if (!isSuccess)
            {
                RaiseLastError();
            }

            WindowsIdentity newIdentity = new WindowsIdentity(token);
            WindowsImpersonationContext impersonatedUser = newIdentity.Impersonate();
保存令牌,然后稍后重试

CloseHandle(token);

如果它是windows服务,您可以在所需的用户帐户下运行它。或者为此服务创建一个特殊帐户。@Den是的,您可以。这并不妨碍我提供一个替代方案。