gpt4 book ai didi

c# - 创建文件时出现 System.UnauthorizedAccessException

转载 作者:太空狗 更新时间:2023-10-30 00:25:42 26 4
gpt4 key购买 nike

我正在尝试编写代码以便记录错误消息。我试图用日期命名文件,并想为每一天创建一个新的日志文件。环顾四周后,我得到了以下代码......

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.SetAttributes(filePath, FileAttributes.Normal) 没有帮助 RemoveReadOnlyAccess(包含在上面的代码中)也没有帮助。当我检查文件夹的属性时,它已被标记为只读,但即使我勾选它,它也会再次出现。我检查了文件夹的权限,除了我无法更改的特殊权限外,一切都是允许的。 任何关于我应该如何进行的建议将不胜感激。 Why is access to the path denied?该链接讨论了一个类似的问题,但我无法使用那里列出的建议来解决我的问题。

感谢您抽出时间来看这个。

最佳答案

你的路径很奇怪:“我的文档”目录必须是“C:\Users\MyName\Documents\”

您可以使用 Environment 以便轻松更正它:

String myDocumentPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

请注意,它将访问运行您的 exe 的用户的“我的文档”文件夹。

第二个错误,CreateDirectory 必须在参数中有路径,而不是文件。像你一样使用将创建一个带有文件名的子目录。所以你不能用这个名字创建一个文件!

试试这个:

String fileName = DateTime.Now.ToString("d", DateTimeFormatInfo.InvariantInfo);

String filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
+ @"\visual studio 2012\projects\training\discussionboard\ErrorLog\";
String fileFullName = filePath + fileName + ".txt";

if (File.Exists(fileFullName ))
{
File.WriteAllText(fileFullName , error);
}
else
{
Directory.CreateDirectory(filePath);

[...]
}
}

关于c# - 创建文件时出现 System.UnauthorizedAccessException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15974590/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com