How to find windows service exe path

前端 未结 9 2021
一整个雨季
一整个雨季 2020-12-25 09:46

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 pa

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-25 09:53

    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);
    

提交回复
热议问题