C# 创建文件时出现 System.UnauthorizedAccessException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15974590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:38:50  来源:igfitidea点击:

System.UnauthorizedAccessException while creating a file

c#exception

提问by anish

I was trying to write a code so that I could log the error messages. I am trying to name the file with the date and would like to create a new log file for each day. After going through a little look around, I came with the following code...

我试图编写一个代码,以便我可以记录错误消息。我试图用日期命名文件,并希望为每一天创建一个新的日志文件。经过一番环顾之后,我得到了以下代码......

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\ErrorLog13.txt' is denied.
     */
}

I found a forum that has discussed about a similar problem but using File.SetAttrributes(filePath, FileAttributes.Normal) did not help neither did the RemoveReadOnlyAccess (included in the code above). When I check the properties of the folder, it has read only marked but even when I tick that off it comes back again. I checked the permissions on the folder and except for the special permission, which I was not able to change, everything is allowed. Any suggestion on how I should proceed would be appreciated. Why is access to the path denied?the link discusses about a similar problem, but I wasn't able to get my thing working with suggestions listed there.

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

Thanks for taking time to look at this.

感谢您花时间看这个。

采纳答案by Xaruth

Your path is strange : "My documents" directory must be "C:\Users\MyName\Documents\"

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

You can use Environment in order to correct it easily :

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

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

Note that it will acces to "My documents" folder of the user that running your exe.

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

Second error, CreateDirectory must have a path in argument, not a file. using like you do will create a sub-directory with the file name. So you can't create a file with this name !

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

Try this :

尝试这个 :

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);

[...]
    }
}

回答by Zdeslav Vojkovic

Some possible reasons:

一些可能的原因:

  • your app is not running under account which is allowed to access that path/file
  • the file is being locked for writing (or maybe reading too) by some other process
  • 您的应用程序未在允许访问该路径/文件的帐户下运行
  • 文件被其他进程锁定以进行写入(或也可能读取)

The first situation could be solved by checking under which account the process is running and verifying that the account has the appropriate rights.

第一种情况可以通过检查进程在哪个帐户下运行并验证该帐户是否具有适当的权限来解决。

The other situation can be solved by checking if any other process is locking the file (e.g. use tools like 'WhosLocking' or 'ProcessExplorer'

另一种情况可以通过检查是否有任何其他进程正在锁定文件来解决(例如,使用“WhosLocking”或“ProcessExplorer”等工具

回答by goku_da_master

I had to run my app as an administrator in order to write to protected folders in c:. For example if debugging your app in visual studio make sure to right click on "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe" and choose "Run As Administrator". Then open your solution from there. My app was trying to write to the root of c:\

我必须以管理员身份运行我的应用程序才能写入 c: 中的受保护文件夹。例如,如果在 Visual Studio 中调试您的应用程序,请确保右键单击“C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe”并选择“以管理员身份运行”。然后从那里打开您的解决方案。我的应用程序试图写入 c:\