我在Visual Studio 2010中有一个用于创建安装工具包(MSI)的安装项目。 我需要更新环境路径以在安装MSI时添加条目。 知道怎么做吗?
我找不到让我访问环境的选项。我唯一看到的可能就是直接编辑注册表。我能做的更好,或者这是我唯一的选择?
由于 贝
答案 0 :(得分:2)
Visual Studio安装项目无法设置环境变量。但是,您可以尝试使用自定义操作。以下是一些示例VBScript代码:
Set WshShell = CreateObject("WScript.Shell")
Set WshEnv = WshShell.Environment("SYSTEM")
WshEnv("Path") = WshEnv("Path") & ";myPath"
您可以将其复制到.VBS文件中,并将该文件添加为安装自定义操作。
答案 1 :(得分:2)
我成功使用Visual Studio(2015)中的安装项目并添加了一个自定义操作来更改注册表,如下所示:
GetEnvironmentVariable() and SetEnvironmentVariable() for PATH Variable
以下代码适用于应该应用于安装项目的提交/安装/卸载操作的自定义操作:
[RunInstaller(true)]
public partial class GRInstallCustomAction : System.Configuration.Install.Installer
{
string environmentKey = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
string pathUrl = "C:\\Program Files (86)\\TargetFolder";
public GRInstallCustomAction()
{
InitializeComponent();
}
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
}
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
public override void Commit(IDictionary savedState)
{
base.Commit(savedState);
string environmentVar = Environment.GetEnvironmentVariable("PATH");
//get non-expanded PATH environment variable
string oldPath = (string)Registry.LocalMachine.CreateSubKey(environmentKey).GetValue("Path", "", RegistryValueOptions.DoNotExpandEnvironmentNames);
var index = oldPath.IndexOf(pathUrl);
if (index < 0)
{
//set the path as an an expandable string
Registry.LocalMachine.CreateSubKey(environmentKey).SetValue("Path", oldPath + ";" + pathUrl, RegistryValueKind.ExpandString);
}
}
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
public override void Rollback(IDictionary savedState)
{
base.Rollback(savedState);
}
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
public override void Uninstall(IDictionary savedState)
{
base.Uninstall(savedState);
//get non-expanded PATH environment variable
string oldPath = (string)Registry.LocalMachine.CreateSubKey(environmentKey).GetValue("Path", "", RegistryValueOptions.DoNotExpandEnvironmentNames);
string removeString = pathUrl + ";";
var index = oldPath.IndexOf(removeString);
if (index < 0)
{
removeString = pathUrl;
index = oldPath.IndexOf(removeString);
}
if (index > -1)
{
oldPath = oldPath.Remove(index, pathUrl.Length);
//set the path as an an expandable string
Registry.LocalMachine.CreateSubKey(environmentKey).SetValue("Path", oldPath, RegistryValueKind.ExpandString);
}
}
}