【发布时间】:2013-04-05 04:06:57
【问题描述】:
我正在尝试编写代码以便记录错误消息。我正在尝试用日期命名文件,并希望为每一天创建一个新的日志文件。经过一番环顾后,我得到了以下代码......
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 (包含在上面的代码中)。当我检查文件夹的属性时,它已标记为只读,但即使我勾选它,它也会再次出现。我检查了文件夹的权限,除了我无法更改的特殊权限外,一切都是允许的。 任何关于我应该如何进行的建议将不胜感激。 Why is access to the path denied? 该链接讨论了类似的问题,但我无法使用那里列出的建议来解决问题。
感谢您花时间看这个。
【问题讨论】:
-
这是服务还是应用程序?目录的用户权限可能与它有关 - 您能否提供有关基础架构的更多信息?如果是服务,是作为域帐户还是本地帐户运行?
-
@Charleh - 这是 Windows 窗体应用程序的一部分。我打算在我所有的 catch 块中调用这个方法。关于用户权限,如果它没有权限,它也不应该创建一个文件夹。它在指定位置创建了一个文件夹名称“ErrorLog”。谢谢。