66
votes

I have a windows service and I need to create directory to store some info. The directory path must be relative to the windows service exe file. How can get this exe file path ?

10
I'm no Windows developer but are you sure you want this? Doesn't such info belong in the user's personal directory, or that of LocalService? - Pekka
@Pekka I'm no Unix Developer but system services (daemons) storing files in user's personal directories sounds downright insane. - BrainSlugs83

10 Answers

42
votes

Tip: If you want to find startup path of installed windows service, look here from registry .

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\ + ServiceName

There are keys about windows service

22
votes

To get path for service you can use Management object. ref: https://msdn.microsoft.com/en-us/library/system.management.managementobject(v=vs.110).aspx http://dotnetstep.blogspot.com/2009/06/get-windowservice-executable-path-in.html

using System.Management;
string ServiceName = "YourServiceName";
using (ManagementObject wmiService = new ManagementObject("Win32_Service.Name='"+ ServiceName +"'"))
                {
                    wmiService.Get();
                    string currentserviceExePath = wmiService["PathName"].ToString();
                    Console.WriteLine(wmiService["PathName"].ToString());
                }
13
votes

Instead of using a directory relative to the executable, and therefore needing admin privileges, why not use the common application data directory, which is accessible through

Environment.GetFolderPath(SpecialFolder.CommonApplicationData)

This way your app doesn't need write access to its own install directory, which makes you more secure.

11
votes

Try this

System.Reflection.Assembly.GetEntryAssembly().Location
8
votes
string exe = Process.GetCurrentProcess().MainModule.FileName;
string path = Path.GetDirectoryName(exe); 

svchost.exe is the executable which runs your service which is in system32. Hence we need to get to the module which is being run by the process.

5
votes

The default directory for a windows service is the System32 folder. In your service, though, you can change the current directory to the directory that you specified in the service installation by doing the following in your OnStart:

        // Define working directory (For a service, this is set to System)
        // This will allow us to reference the app.config if it is in the same directory as the exe
        Process pc = Process.GetCurrentProcess();
        Directory.SetCurrentDirectory(pc.MainModule.FileName.Substring(0, pc.MainModule.FileName.LastIndexOf(@"\")));

Edit: an even simpler method (but I haven't tested yet):

System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);
3
votes

This did the trick for me

Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);    
0
votes

This will return you the correct path even if running under LocalSystem account which defaults to system32:

System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);
-4
votes

If you want to get access of Program Files folder or any other using programming you should use the below code which is provide rights to specific folder.

 private bool GrantAccess(string fullPath)
        {
            DirectoryInfo dInfo = new DirectoryInfo(fullPath);
            DirectorySecurity dSecurity = dInfo.GetAccessControl();
            dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
            dInfo.SetAccessControl(dSecurity);
            return true;
        }