In my previous post, I mentioned that using the Microsoft Visual Studio Setup and Deployment Wizard's Registry Editor to add in your custom application's path to the system path environment variable has an unfortunate side effect - the uninstaller will delete the system path variable.
A better but longer way is to write your own custom action program to add in your custom application's path to the system path environment variable during installation. In the custom action program (I call it AddPath and I use C# in my example code), I call a SetPathVariable function from main as shown below to do the job.
class Program
{
static void Main(string[] args)
{
try
{
//Call this function to add in my custom application's location to the system path variable
SetPathVariable();
}
catch
{
}
finally
{
}
}
The SetPathVariable will read in the AddPath program's command line arguments to find the custom application's location.
#region public methods
public static void SetPathVariable()
{
//Read and place the command line arguments into a string array.
//The custom application path is the first argument.
string[] cmd_args = System.Environment.GetCommandLineArgs();
//Now call this function to append the custom application's folder
//to the system Path environment variable
AppendPathVariable(cmd_args[0]);
}
public static void AppendPathVariable(string appPath)
{
try
{
//Filter custom application's path
string loc = GetPathOnly(appPath);
//Get the current value of the Path environment variable
string Value = System.Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine);
//Only append the custom application's path if it is not already in
//the system Path environment variable.
if (Value.ToUpper().Contains(loc.ToUpper()) == false)
{
Value = Value + ";" + loc;
System.Environment.SetEnvironmentVariable("Path", Value, EnvironmentVariableTarget.Machine);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
//This function simply ensures that the input string is a valid
//path string
public static string GetPathOnly(string url)
{
string outputStr = string.Empty;
string ipurl = url;
char[] delimiter = { '\\'};
string[] values = ipurl.Split(delimiter);
for (int i = 0; i <values.Length - 1; i++)
{
if (i == 0)
{
outputStr = values[i];
}
else
{
outputStr = outputStr + @"\" + values[i];
}
}
return outputStr;
}
#endregion
}
In the Setup and Deployment project, you need to add in this AddPath executable in the Custom Actions Commit phase as shown in the figure below.
In addition, you have to set the Arguments property for AppPath to “[OriginalDatabase]<>[TARGETDIR]<>[ComputerName]", as shown below.
Now your installer will be able to add in your custom application's path to the System Path environment variable correctly without having it deleted by the uninstaller.