2017-05-22 71 views
0

我試圖在我的文檔中創建一個新文件夾,並向它添加一個錯誤日誌文本文件,但我得到一個UnauthrizedAccessException。我如何給創建這個文件夾並寫入它的權限?UnauthrizedAccessException當創建和寫入文件夾

我的代碼是用於創建我的錯誤日誌

 string currentContent = String.Empty; 
     string message = string.Format("Time: {0}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")); 




     message += "-----------------------------------------------------------"; 

     message += Environment.NewLine; 
     message += string.Format($"Message: {errorText} {ex.Message}"); 

     message += Environment.NewLine; 
     message += string.Format($"On Line: {currentLine} Test name {methodName}"); 
     string filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\ErrorLog\ErrorLogAutomatedTesting.txt"; 

     if (File.Exists(filePath)) 
     { 
      currentContent = File.ReadAllText(filePath); 
     } 
     else 
      System.IO.Directory.CreateDirectory(filePath); 
     Thread.Sleep(2000); 

     File.WriteAllText(filePath, message + currentContent); 
+0

哪個用戶是運行的應用程序?它與「文檔」文件夾所在的用戶帳戶不同嗎? – benPearce

回答

1

您正在創建一個目錄與文件名ErrorLogAutomatedTesting.txt如下。所以它不會是一個文件,而是一個目錄。這是因爲filePath變量也包含文件的名稱。所以嘗試沒有它:

var dir = System.IO.Path.GetDirectoryName(filePath); 
System.IO.Directory.CreateDirectory(dir); 
+0

這解決了我的問題。非常感謝你 :) –