[英]Unauthorized Access Exception - Access to the Path Denied while copying file to other Directory in C#
[英]Copying a file, using impersonator, throw an Unauthorized Access Exception
我正在使用此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”。
在模拟之前,当前用户可以访问源文件路径,但不能访问目标文件路径。
模仿后,情况正好相反:模拟用户可以访问目标文件路径,但不能访问源文件路径。
如果文件不是太大,我的想法如下:
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
者暂时更改当前线程的标识。 感谢@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();
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.