エラーメッセージをログに記録できるようにコードを記述しようとしていました。ファイルに日付の名前を付けようとしていて、毎日新しいログ ファイルを作成したいと考えています。少し調べてみたところ、次のコードがありました...
class ErrorLog
{
public void WriteErrorToFile(string error)
{
//http://msdn.microsoft.com/en-us/library/aa326721.aspx refer for more info
string fileName = DateTime.Now.ToString("dd-MM-yy", DateTimeFormatInfo.InvariantInfo);
//@ symbol helps to ignore that escape sequence thing
string filePath = @"c:\users\MyName\mydocuments\visual studio 2012\projects\training\" +
@"discussionboard\ErrorLog\" + fileName + ".txt";
if (File.Exists(filePath))
{
// File.SetAttributes(filePath, FileAttributes.Normal);
File.WriteAllText(filePath, error);
}
else
{
Directory.CreateDirectory(filePath);
// File.SetAttributes(filePath, FileAttributes.Normal)
//Throws unauthorized access exception
RemoveReadOnlyAccess(filePath);
File.WriteAllText(filePath, error);
}
}
public static void RemoveReadOnlyAccess(string pathToFile)
{
FileInfo myFileInfo = new FileInfo(pathToFile);
myFileInfo.IsReadOnly = false;
myFileInfo.Refresh();
}
/*Exception thrown:
* UnAuthorizedAccessException was unhandled.
* Access to the path 'c:\users\anish\mydocuments\visual studio 2012\
* projects\training\discussionboard\ErrorLog\04\12\2013.txt' is denied.
*/
}
同様の問題について議論しているフォーラムを見つけましたが、 File.SetAttrributes(filePath, FileAttributes.Normal) を使用しても役に立たず、RemoveReadOnlyAccess (上記のコードに含まれています) も役に立ちませんでした。フォルダのプロパティを確認すると、読み取り専用とマークされていますが、チェックを外しても再び戻ってきます。フォルダーのアクセス許可を確認しましたが、変更できなかった特別なアクセス許可を除いて、すべてが許可されています。どのように進めるべきかについての提案をいただければ幸いです。 パスへのアクセスが拒否されるのはなぜですか? リンクは同様の問題について説明していますが、そこにリストされている提案で自分のことを機能させることができませんでした。
これを見ていただきありがとうございます。