Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.UnauthorizedAccessException while creating a file

Tags:

c#

exception

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\ErrorLog\04\12\2013.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.

Thanks for taking time to look at this.

like image 271
anish Avatar asked Apr 12 '13 14:04

anish


People also ask

What is System UnauthorizedAccessException?

An UnauthorizedAccessException exception is typically thrown by a method that wraps a Windows API call. To find the reasons for the exception, examine the text of the exception object's Message property. UnauthorizedAccessException uses the HRESULT COR_E_UNAUTHORIZEDACCESS , which has the value 0x80070005.


1 Answers

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

[...]
    }
}
like image 136
Xaruth Avatar answered Sep 19 '22 23:09

Xaruth