Why is StreamWriter not working on Windows service?

I have this simple code that writes a file 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 great in a Windows Forms application. However, using the instsrv and srvany trick , I made it a Windows Service. The service is running fine, accessing the database, executing requests, and that's it ... Except that StreamWriter. The magazine just doesn't update as it should. Any ideas why?

+1


a source to share


4 answers


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



So check the properties dialog for the service and check the Login tab to see what it goes into.

+6


a source


Possible reasons:



  • Constants.APP_PATH points to a mapped drive - services do not start in the same environment as the logged on user, so the path may not be valid
  • Permissions - Depending on which user is running the service, they may not have access to the same set of directories as the WinForms application.
+2


a source


Without additional information, nothing can help. How does it not work exactly? Are you getting an exception? Does he just fail?

Just a couple of tips ...

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

. Like this:

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

      

2) Insert the notebook into the block using()

. For instance:

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

      

3) Make sure the account the service is using has access to create / overwrite files in this directory. Often times, service accounts such as LOCAL_SYSTEM

or NETWORK_SERVICE

will not have the same permissions as user accounts. This might 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-defined, such as mapping drives to a network share. Drive mappings don't cover users, so this can be a problem as well.

+2


a source


Without further information, I would assume that the account your service is running on does not have the right to open the file for writing.

0


a source







All Articles