7

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.

Community
  • 1
  • 1
haku
  • 4,105
  • 7
  • 38
  • 63
  • 2
    Is this a service or an application? The user rights to the directory may have something to do with it - can you provide more information on the infrastructure? If it's a service, is it running as a domain account or local account? – Charleh Apr 12 '13 at 15:00
  • @Charleh - This is a a part of a windows form application. I am planning to call this method in all of my catch blocks. Regarding the user rights, if it did not have the rights should it not fail to create a folder as well. It has created a folder name "ErrorLog" at the specified location. Thanks. – haku Apr 12 '13 at 15:25

4 Answers4

6

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

[...]
    }
}
haku
  • 4,105
  • 7
  • 38
  • 63
Xaruth
  • 4,034
  • 3
  • 19
  • 26
  • Ya after you mentioned, it looked kind of strange to me. However, when I specify the path just like I have done up there, it is able to create "ErrorLog" folder which previously was not there, the problem is when it comes to creating a file within that folder. Any idea if I am doing the file creation part correctly? – haku Apr 12 '13 at 15:17
  • I tried what you said and that made sense to me, but still the same error. Also, I initially had my dates converted to string in "dd/mm/yy" and the "/" is not allowed in the file name so I thought that might be the problem, I changed it to "mm-dd-yy" but that did not help either. Any idea how would I go about checking/changing permission of the user account I am using? – haku Apr 12 '13 at 15:45
  • 1
    It worked! Thanks a lot, you are awesome :). Seems like the problem was somewhere with the pathname I have used, when I changed it to the way you have done Environment.GetFolderPath... it worked! Appreciated! :) Too bad I can't vote up your answer at this time cuz of my reputation :( – haku Apr 12 '13 at 15:50
4

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'

Zdeslav Vojkovic
  • 14,391
  • 32
  • 45
  • 1
    Thanks for your response. I am pretty sure that I am using a user account with admin rights. If it did not have rights, should it not be like it had to fail to create the folder as well? It got the folder created, but not the file. That is the new file that the application has to create, so I think that rules out the possibility for being locked as well, isn't it? – haku Apr 12 '13 at 15:22
1

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

goku_da_master
  • 4,257
  • 1
  • 41
  • 43
1

Check your antivirus, it might be blocking the file creation.

Sebastian
  • 301
  • 3
  • 4