繁体   English   中英

确定应用程序位置的正确方法是什么?

[英]What is the proper way to determine an application's location?

我正在用C#编写一个Windows服务,它会生成我正在编写的另一个应用程序的多个实例。 应用程序有可能安装在计算机上的任何位置。 让服务知道应用程序所在位置的最佳方法是什么?

如果需要找到安装服务的文件夹,可以使用以下代码

this.GetType().Assembly.Location

如果您需要找到安装了其他应用程序的文件夹,则应向Windows安装程序发出请求

[DllImport("MSI.DLL", CharSet = CharSet.Auto)]
private static extern UInt32 MsiGetComponentPath(
    string szProduct,
    string szComponent,
    StringBuilder lpPathBuf,
    ref int pcchBuf);

private static string GetComponentPath(string product, string component)
{
    int pathLength = 1024;
    StringBuilder path = new StringBuilder(pathLength);
    MsiGetComponentPath(product, component, path, ref pathLength);
    return path.ToString();
}

如果您的意思是该服务启动了另一个应用程序,那么; 选项:

  • 使用配置文件配置服务; 把路径放在那里
  • 在安装过程中将一些内容放入注册表
  • 使用类似于COM / COM +注册的东西
  • 考虑 GAC,如果其他应用程序是.NET(虽然我不是粉丝......)
  • 环境变量?

就个人而言,我喜欢配置文件选项; 它简单易用,并允许多个独立(并排)服务和应用程序安装

using System.IO;
using System.Windows.Forms;

string appPath = Path.GetDirectoryName(Application.ExecutablePath)

这是一个应用程序(上图)。

对于asp.net项目:

using System.Web;

HttpContext.Current.Server.MapPath( "place arguments here" );

System.Environment.CurrentDirectory

在安装期间编写注册表变量,这样在提供升级时,您可以读回先前写入的值,并默认为用户先前选择的文件夹。

暂无
暂无

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

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