When you need to obtain the path of the current service in Windows service, you cannot simply use environment. currentdirectory to obtain the current path, because the directory started by Windows service is in C:/Windows/system32. If you need to detect a configuration file in your service, you cannot obtain the path of this configuration file. There are two solutions:
1. install your configuration file in the System32 directory.
2. Obtain the installation path of the service through the Registry in your service
/*
After the Windows service is installed on the system, a directory is created with the servicename of the service under "HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Services \ [servicename]" in the registry, the "ImagePath" section appears in the directory. The installation path of the service is saved here.
*/
2 /// <summary>
3 // obtain the installation path of the service. 4 /// </Summary>
5 // <Param name = "servicename"> service name </param>
6 /// <returns> service installation path </returns>
7 public static string getwindowsserviceinstallpath (string servicename)
8 {
9 string key = @ "SYSTEM \ CurrentControlSet \ Services \" + servicename;
10 string Path = registry. localmachine. opensubkey (key). getvalue ("ImagePath"). tostring ();
11 Path = path. Replace ("\" ", String. Empty); // replace double quotation marks
12 fileinfo Fi = new fileinfo (PATH );
13 return fi. Directory. tostring ();
14}
15