简体   繁体   中英

Why doesn't StreamWriter work in a Windows Service?

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?

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.

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.

没有更多信息,我想您的服务所运行的帐户无权打开该文件进行写入。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM