Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows service can't write to %LOCALAPPDATA%

I have built an app that works only when not run as a Windows service. Well, the service runs, but it doesn't do what it should. The service uses the Local Service account. So to kick off debugging, I thought I'd start with something simple: have it create a directory when it starts:

Directory.CreateDirectory(
    Environment.SpecialFolder.LocalApplicationData + "\\MyService");

When I started the service, it stopped almost immediately and Windows reported that fact. When I commented out the above statement, recompiled and re-installed, the service ran without stopping.

Obviously the above line throws an exception of some sort. I have no way of logging the error because I can't write to the file system. Any ideas why Local Service can't create a directory in its own %LOCALAPPDATA%?

like image 316
Steve Avatar asked Mar 31 '12 08:03

Steve


2 Answers

You should use GetFolderPath with LocalApplicationData like so:

string folderName = Path.Combine(Environment.GetFolderPath(
    Environment.SpecialFolder.LocalApplicationData), 
    "MyService");

Directory.CreateDirectory(folderName)
like image 109
BluesRockAddict Avatar answered Oct 20 '22 06:10

BluesRockAddict


I think this might be because there is no special folder. When running as the local service account you are running under that user, not the logged in user. so you are requesting a special folder that probably wont exist, as I don't think the local service has a profile. (I may be wrong) - I was wrong :p

Just in case anyone pops by:

C:\Windows\ServiceProfiles\LocalService

is the local service profile folder, so it will end up in there.

If you want to debug it surround that line with a try catch, and then write the error to a file:

try
{
    Directory.CreateDirectory(Environment.SpecialFolder.LocalApplicationData + "\\MyService");
}
catch (Exception ex)
{
    System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\MyServicelog.txt",true);
    file.WriteLine(ex.Message);
    file.Close();
}

At least then you can see whats causing the error

Martyn

like image 4
SmithMart Avatar answered Oct 20 '22 06:10

SmithMart