2017-05-22 7 views
0

ドキュメントに新しいフォルダを作成しようとしましたが、エラーログテキストファイルを追加しようとしましたが、UnauthrizedAccessExceptionが表示されます。このフォルダを作成して書き込むにはどのようにアクセスできますか?あなたは、ファイル名ErrorLogAutomatedTesting.txtのディレクトリを作成している私のエラーログフォルダの作成と書き込みに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

どのユーザーがアプリケーションを実行していますか? 「Documents」フォルダの下にあるユーザーアカウントとは異なりますか? – benPearce

答えて

1

を作成するために、次のように

私のコードです。したがって、ファイルではなく、ディレクトリになります。これは、filePath変数にもファイルの名前が含まれているためです。だからそれを試してみてください:

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

これは私の問題を解決しました。どうもありがとうございました :) –

関連する問題