我正在尝试编写代码以便记录错误消息。我正在尝试用日期命名文件,并希望为每一天创建一个新的日志文件。经过一番环顾后,我得到了以下代码......
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 (包含在上面的代码中)。当我检查文件夹的属性时,它已标记为只读,但即使我勾选它,它也会再次出现。我检查了文件夹的权限,除了我无法更改的特殊权限外,一切都是允许的。任何关于我应该如何进行的建议将不胜感激。 为什么访问路径被拒绝?该链接讨论了类似的问题,但我无法使用那里列出的建议来解决问题。
感谢您花时间看这个。