1

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

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等文件夹中的文件时,原始用户可以访问但模仿者没有。

尝试从此类位置复制文件时遇到的异常是:

mscorlib.dll 中出现“System.UnauthorizedAccessException”类型的未处理异常附加信息:对路径“C:\Users\username\Documents\file.txt”的访问被拒绝。

4

2 回答 2

3

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

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

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

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

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

IE:

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

这里使用的方法和类:

于 2016-04-20T12:33:54.260 回答
1

感谢@Uwe Keim 的想法,以下解决方案完美运行:

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

        using (MemoryStream ms = new MemoryStream())
        {
            using (var file = new FileStream(sourceFullFileName, FileMode.Open, FileAccess.Read))
            {
                 byte[] bytes = new byte[file.Length];
                 file.Read(bytes, 0, (int)file.Length);
                 ms.Write(bytes, 0, (int)file.Length);
             }

            using (new Impersonator("username", "domain", "pwd"))
            {
                 using (var file = new FileStream(targetFullFileName, FileMode.Create, FileAccess.Write))
                 {
                       byte[] bytes = new byte[ms.Length];
                       ms.Read(bytes, 0, (int)ms.Length);
                       file.Write(bytes, 0, bytes.Length);
                       ms.Close();
                 }
            }
        }
    }
于 2016-04-20T07:53:46.577 回答