0

I am currently porting a C# application from .NET Framework to .NET Core, to be able to run it on Linux. At some point this application starts another program in a separate process, using the System.Diagnostics.Process class. While this works well in general, that particular programm needs to be run with a modified PATH environment variable. This is what I did for Windows (paths changed for testing on Linux):

string directory = "/tmp";
ProcessStartInfo processStartInfo = new ProcessStartInfo
{
    Arguments = "-c \"echo $PATH\"",
    FileName = "/bin/bash",
};
processStartInfo.EnvironmentVariables["PATH"] += ";" + directory;
Process.Start(processStartInfo);

Unfortunately Linux uses a colon (":") as a path separator, thus the program produces

/usr/local/bin:/usr/bin:/bin:/usr/games;/tmp

instead of the desired output

/usr/local/bin:/usr/bin:/bin:/usr/games:/tmp

My question now is: How do I properly update the PATH variable in a safe, cross-platform way? Is there some system-dependent property to retrieve the separator character (like Environment.NewLine for line breaks or Path.DirectorySeparatorChar for slashes), or do I have to check for the current OS manually?

janw
  • 8,758
  • 11
  • 40
  • 62

2 Answers2

2

This should be what you need:

processStartInfo.EnvironmentVariables["PATH"] += Path.PathSeparator + directory;
Suiden
  • 622
  • 4
  • 17
1

Just do a check if you're running on linux. if so, use ":" instead of ";".

int platform = (int) Environment.OSVersion.Platform;
bool isLinux = (platform == 4) || (platform == 6) || (platform == 128);

string directory = "/tmp";
ProcessStartInfo processStartInfo = new ProcessStartInfo
{
    Arguments = "-c \"echo $PATH\"",
    FileName = "/bin/bash",
};
processStartInfo.EnvironmentVariables["PATH"] += (isLinux ? ":" : ";") + directory;
Process.Start(processStartInfo);

reference: Detect Linux

CarCar
  • 680
  • 4
  • 13