C#Windows服务 - 从App.config启动.exe

时间:2017-07-26 14:31:43

标签: c# windows-services windows-installer

我使用以下代码从Windows服务执行.exe文件。

System.Diagnostics.Process.Start(path);

现在,我将路径硬编码为@'C:\ Program Files \ Server \ Test.exe' 它工作正常。

现在,我想避免硬编码。当我只使用Test.exe时,它会转到C:\ Windows \ System32。

如何从Windows服务动态获取已安装的路径?或者我如何从App.config文件中读取路径?

3 个答案:

答案 0 :(得分:5)

Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)

答案 1 :(得分:1)

如果您的.net一直向下(即您的Windows服务是.net应用程序),那么您可以使用Assembly.GetEntryAssembly(来自System.Reflection命名空间):

var entryAssembly = Assembly.GetEntryAssembly();
var launchLocation = entryAssembly.Location;

或者你可以查看你正在执行的AppDomain(假设你没有做任何聪明的事情!)

var appDomain = AppDomain.CurrentDomain;
var launchLocation = appDomain.BaseDirectory;

一个简单的控制台应用程序:

static void Main(string[] args)
{
    var entryAssembly = Assembly.GetEntryAssembly();
    var launchLocationFromAssembly = entryAssembly.Location;


    var appDomain = AppDomain.CurrentDomain;
    var launchLocationFromAppDomain = appDomain.BaseDirectory;

    Console.WriteLine(launchLocationFromAssembly);
    Console.WriteLine(launchLocationFromAppDomain);
}

提供以下输出:

  

c:\ users \ robertwray \ documents \ visual studio 2015 \ Projects \ ConsoleApplication4 \ ConsoleApplication4 \ bin \ Debug \ ConsoleApplication4.exe

     

c:\ users \ robertwray \ documents \ visual studio 2015 \ Projects \ ConsoleApplication4 \ ConsoleApplication4 \ bin \ Debug \

这意味着如果您确实使用Assembly来检索路径,则需要使用以下内容删除可执行文件的名称:

var launchPathFromAssembly = Path.GetDirectoryName(launchLocationFromAssembly);

答案 2 :(得分:1)

您可以使用

AppDomain.CurrentDomain.BaseDirectory