c# - 使用模仿者复制文件,抛出未经授权的访问异常

标签 c# impersonation networkcredentials

我正在使用 this Impersonator class将文件复制到具有访问权限的目录。

public void CopyFile(string sourceFullFileName,string targetFullFileName)
{
    var fileInfo = new FileInfo(sourceFullFileName);

    try
    {
        using (new Impersonator("username", "domain", "pwd"))
        {
            // The following code is executed under the impersonated user.
            fileInfo.CopyTo(targetFullFileName, true);
        }
    }
    catch (IOException)
    {
        throw;
    }
}

这段代码几乎可以完美运行。 我面临的问题是当 sourceFullFileName 是一个位于像 C:\Users\username\Documents 这样的文件夹中的文件时,原始用户可以访问但模仿者没有。

我在尝试从这样的位置复制文件时遇到的异常是:

An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll Additional information: Access to the path 'C:\Users\username\Documents\file.txt' is denied.

最佳答案

在模拟之前,当前用户可以访问源文件路径但不能访问目标文件路径。

模拟之后,情况恰恰相反:被模拟的用户可以访问目标文件路径,但不能访问源文件路径。

如果文件不是太大,我的想法是:

public void CopyFile(string sourceFilePath, string destinationFilePath)
{
    var content = File.ReadAllBytes(sourceFilePath);

    using (new Impersonator("username", "domain", "pwd"))
    {
        File.WriteAllBytes(destinationFilePath, content);
    }
}

即:

  1. 将源文件路径中的所有内容读取到内存中的一个字节数组中。
  2. 模仿。
  3. 将内存中字节数组的所有内容写入目标文件路径。

这里使用的方法和类:

关于c# - 使用模仿者复制文件,抛出未经授权的访问异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36736528/

相关文章:

c# - 如何使用 MVVM 将焦点设置为 WPF 控件?

c++ - ImpersonateLoggedOnUser 无法在 Windows 服务中工作

asp.net - Exchange Web 服务、带有 Windows 身份验证的 ASP.NET、IIS 8.5 和模拟

c# - 是否可以让 SQL 中的 CLR 函数采用特定的 Windows 标识?

iphone - 如何在 iOS 应用中安全地包含服务器凭据

c# - WebProxy 错误 : Proxy Authentication Required

c# - 如何从 C# 中确定性地处理托管 C++/CLI 对象?

C# 夏令时 DateTime 开关

c# - Automapper:ForMember 中的复杂 if else 语句

http - 在黑莓中发送带有凭据的 HTTP 请求