简体   繁体   English

获取应用程序路径-WPF与Windows Service

[英]Getting Application Path - WPF versus Windows Service

I need to know a reliable way I can determine the folder that a windows service was started from. 我需要知道一种可靠的方法,可以确定Windows服务是从哪个文件夹启动的。 The way of determining this seems to be different than the way you'd determine it in a WPF applciaiton. 确定它的方式似乎与您在WPF应用程序中确定它的方式不同。

More Details (optional reading): 更多详细信息(可选阅读):

I have an embedded sql database that is used by both a WPF application and a windows service. 我有一个WPF应用程序和Windows服务都使用的嵌入式sql数据库。

During development, the relative path to the database has been different for both projects because they have been running from their own debug directories while accessing this same embedded database. 在开发过程中,这两个项目到数据库的相对路径都不同,因为它们在访问同一嵌入式数据库时都从自己的调试目录运行。

Now, I'm trying to create an installer. 现在,我正在尝试创建一个安装程序。 I've moved both the windows service executable and wpf applications executable to the same root directory. 我已经将Windows服务可执行文件和wpf应用程序可执行文件都移到了相同的根目录。

In the wpf applciation, I'm successfully creating a database connection string that points to the embedded database, but in the windows service I am not successfully creating this connection string. 在wpf应用程序中,我成功创建了指向嵌入式数据库的数据库连接字符串,但是在Windows服务中,我未成功创建此连接字符串。

Get your main assembly with Assembly.GetEntryAssembly. 使用Assembly.GetEntryAssembly获取主装配。 There, you'll have the Location property telling where your code is installed. 在这里,您将拥有Location属性,可以告诉您代码的安装位置。

Note that the current directory of a service is c:\\windows\\system32 (assuming default install dir). 请注意,服务的当前目录为c:\\ windows \\ system32(假定默认安装目录)。

To get the directory that the windows service was installed in, you can use : 要获取Windows服务的安装目录,可以使用:

        private string GetExeDir()
    {
        System.Reflection.Assembly ass = System.Reflection.Assembly.GetExecutingAssembly();
        string codeBase = System.IO.Path.GetDirectoryName(ass.CodeBase);
        System.Uri uri = new Uri(codeBase);
        return uri.LocalPath;
    }

I think you are attacking the problem from the wrong direction. 我认为您是从错误的方向攻击问题。 I would make the path to the database configurable in the config file for both the WPF app and the Windows Service. 我将在WPF应用程序和Windows Service的配置文件中都可以配置数据库的路径。 Then your code would simply build the connection string with the path from the config file. 然后,您的代码只需使用配置文件中的路径构建连接字符串。

Alternatively, you might think about using an environment variable and setting that environment variable in your installer. 另外,您可能会考虑使用环境变量并在安装程序中设置该环境变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM