我有一个Windows服务,我需要创建目录来存储一些信息.目录路径必须相对于Windows服务exe文件.怎么能得到这个exe文件路径?
Inc*_*ito 105
您可以使用AppDomain.CurrentDomain.BaseDirectory
TC *_*eri 36
提示:如果要查找已安装的Windows服务的启动路径,请从注册表中查看.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\ + ServiceName
Run Code Online (Sandbox Code Playgroud)
关于Windows服务有关键
Abh*_*hay 16
要获取服务路径,可以使用Management对象.参考:https ://msdn.microsoft.com/en-us/library/system.management.managementobject(v= vs.110).aspx http://dotnetstep.blogspot.com/2009/06/get-windowservice-可执行文件路径,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());
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*art 13
而不是使用相对于可执行文件的目录,因此需要管理员权限,为什么不使用可通过的公共应用程序数据目录
Environment.GetFolderPath(SpecialFolder.CommonApplicationData)
Run Code Online (Sandbox Code Playgroud)
这样您的应用程序就不需要对其自己的安装目录的写访问权限,这使您更安全.
ram*_*ari 10
试试这个
System.Reflection.Assembly.GetEntryAssembly().Location
Run Code Online (Sandbox Code Playgroud)
小智 8
string exe = Process.GetCurrentProcess().MainModule.FileName;
string path = Path.GetDirectoryName(exe);
Run Code Online (Sandbox Code Playgroud)
svchost.exe是运行您的服务的可执行文件,该服务位于system32中.因此,我们需要访问由该进程运行的模块.
Windows服务的默认目录是System32文件夹.但是,在您的服务中,您可以通过在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(@"\")));
Run Code Online (Sandbox Code Playgroud)
编辑:一个更简单的方法(但我尚未测试):
System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
84899 次 |
最近记录: |