Question

I have this simple code that records appends a log to a text file:

    public static void RecordToFile(string filename, Log log)
    {
            TextWriter textWriter = new StreamWriter(Constants.APP_PATH + 
                "\\" + filename, true);
            textWriter.WriteLine(log.ToString());
            textWriter.Close();
    }

This works perfectly in a Windows Forms application. However, using the instsrv and srvany trick, I made this a Windows Service. The service runs fine, accesses the database, performs queries and all... Except for this StreamWriter. The log just doesn't get updated as it should. Any ideas why?

Was it helpful?

Solution

Most likely the service is running under user credentials that does not have access rights to that directory.

So check the properties dialog for the service, and check the Log On tab to see what it logs on as.

OTHER TIPS

Possible Reasons:

  1. Constants.APP_PATH is pointing to a mapped drive - services don't run in the same environment as a logged-in user, so the path may not be valid
  2. Permissions - depending on what user the service is running as, it may not have access to the same set of directories that the WinForms app did

Without more information there isn't much that anyone can help with. In what way, exactly, does it not function? Do you get an exception? Does it just fail silently?

Just a couple of tips...

1) Don't use string concatenation to create file paths. Use System.IO.Path.Combine instead. Like this:

TextWriter textWriter = new StreamWriter(
    System.IO.Path.Combine(Constants.APP_PATH, filename), true);

2) Enclose your writer in a using() block. Like so:

using(TextWriter textWriter = new StreamWriter(
        System.IO.Path.Combine(Constants.APP_PATH, filename), true))
{
    textWriter.WriteLine(log.ToString());
}

3) Verify that the account the service is using has access to create/overwrite files in that directory. Often service accounts like LOCAL_SYSTEM or NETWORK_SERVICE aren't going to have the same permissions as user accounts would. This could explain why it works as a user but not as a service. It could also be that your APP_PATH constant points to something user specific, like a drive mapping to a network share. Drive mappings don't span users, so this could also be an issue.

Without any more information I'd guess that the account your service is running under doesn't have rights to open the file for writing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top