views:

239

answers:

1

Hi,

I am creating a Windows Service which I want to use NLog with. I want the logs to be written to the install location of the service say something like:

PathToInstalledService\Logs\MyLog.txt

This is of course going to require administrator priveledges. So my question is, when creating the install for the Service, what account should I use on the ServiceProcessInstaller. I have been currently using LocalService, but this account does not have the required elevation.

Thanks.

+1  A: 

During installation you should change the permissions of the 'Logs' directory to allow your service account to write files. Use the account with the least privileges needed to perform your services function, generally the NETWORK SERVICE account.

You can do this from an install class on the service:

 void Installer1_AfterInstall(object sender, InstallEventArgs e)
 {
  string myAssembly = Path.GetFullPath(this.Context.Parameters["assemblypath"]);
  string logPath = Path.Combine(Path.GetDirectoryName(myAssembly), "Logs");
  Directory.CreateDirectory(logPath);
  ReplacePermissions(logPath, WellKnownSidType.NetworkServiceSid, FileSystemRights.FullControl);
 }

 static void ReplacePermissions(string filepath, WellKnownSidType sidType, FileSystemRights allow)
 {
  FileSecurity sec = File.GetAccessControl(filepath);
  SecurityIdentifier sid = new SecurityIdentifier(sidType, null);
  sec.PurgeAccessRules(sid); //remove existing
  sec.AddAccessRule(new FileSystemAccessRule(sid, allow, AccessControlType.Allow));
  File.SetAccessControl(filepath, sec);
 }
csharptest.net
Should this code be called on the initialization of the ProjectInstaller class?
James
I would create an install util class for this and add the service installer to it: http://msdn.microsoft.com/en-us/library/system.configuration.install.installer.aspx
csharptest.net
Any idea's how I can get the path to my specific install folder from within the Installer class?
James
This does what I need, I call this method in the OnAfterInstall event of my custom installer. However, at the moment I am hard-coding the install path in if you could update your solution with how I can get the install dir programmatically that would be ideal.
James
Just use the AfterInstall event above. It should be a member of the Install class, or replace 'this.Context' with 'installer.Context'.
csharptest.net
Thanks I was playing around with the Context.Parameters just wasn't sure what the name of the one I would be looking for was! I will give this a try
James