创建文件时System.UnauthorizedAccessException

NoS*_*ler 4 c# exception

我试图编写代码,以便我可以记录错误消息.我试图用日期命名文件,并希望每天创建一个新的日志文件.经过一番浏览后,我带来了以下代码......

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.
     */
}
Run Code Online (Sandbox Code Playgroud)

我找到了一个讨论过类似问题的论坛,但使用File.SetAttrributes(filePath,FileAttributes.Normal)对RemoveReadOnlyAccess(包含在上面的代码中)没有帮助.当我检查文件夹的属性时,它只读取了标记,但即使我勾选它也会再次返回.我检查了文件夹的权限,除了特殊权限,我无法更改,一切都被允许.任何关于我应该如何进行的建议将不胜感激. 为什么拒绝访问路径?该链接讨论了类似的问题,但我无法使用其中列出的建议.

感谢您花时间看看这个.

Xar*_*uth 5

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

您可以使用Environment来轻松纠正它:

String myDocumentPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Run Code Online (Sandbox Code Playgroud)

请注意,它将访问运行您的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);

[...]
    }
}
Run Code Online (Sandbox Code Playgroud)