我正在使用 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);
}
}
即:
- 将源文件路径中的所有内容读取到内存中的一个字节数组中。
- 模仿。
- 将内存中字节数组的所有内容写入目标文件路径。
这里使用的方法和类:
-
File.ReadAllBytes
将所有内容读入内存。 -
File.WriteAllBytes
将内存中的所有内容写入文件。 -
Impersonator
临时更改当前线程的标识。
关于c# - 使用模仿者复制文件,抛出未经授权的访问异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36736528/