簡體   English   中英

使用模仿器復制文件會拋出未經授權的訪問異常

[英]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);
    }
}

即:

  1. 將源文件路徑中的所有內容讀入內存中的字節數組。
  2. 做模仿。
  3. 將內存中字節數組中的所有內容寫入目標文件路徑。

這里使用的方法和類:

感謝@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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM