![](/img/trans.png)
[英]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.