System.UnauthorizedAccessException while creating a file

后端 未结 3 736
遥遥无期
遥遥无期 2021-01-18 14:26

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 g

相关标签:
3条回答
  • 2021-01-18 14:43

    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'

    0 讨论(0)
  • 2021-01-18 14:49

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

    You can use Environment in order to correct it easily :

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

    Note that it will acces to "My documents" folder of the user that running your 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 !

    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);
    
    [...]
        }
    }
    
    0 讨论(0)
  • 2021-01-18 15:01

    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:\

    0 讨论(0)
提交回复
热议问题