Question

I have a program that watches processes and restarts them if they close or fail. It started as a work project but I took it home to keep game servers up on my home server, i.e. Minecraft, Terraria and more recently Cube World. The program is standalone and sits on my desktop. When it starts Cube World's Server.exe, all of the files that the exe would normally create in Cube World's folder are created on the desktop. My guess is that my program has a working directory of the desktop so any child processes it starts (like Server.exe) will have the same working directory. The problem is not specific to just Cube World's server at home. This program plays keep alive with important back end processes at work.

If I'm starting a Process in C# using ProcessStartInfo how can ensure that the working directory of the started process is the directory the exe is in? The Process may be started with a relative path name or may be on the System PATH making this a little more difficult.

Was it helpful?

Solution

Use ProcessStartInfo.WorkingDirectory in combination with Check if an executable exists in the windows path to determine the path to the executable.

You might need to first check for relative paths, which I think should also handle absolute paths (I have not tested the following code, but it looks ok to me):

string myAppPath = System.Reflection.Assembly.GetEntryAssembly().Location;
if (File.Exists(Path.Combine(myAppPath, pathToExe)))
{
    workDir = Path.GetDirectoryName(Path.Combine(myAppPath, pathToExe));
}
else 
{
    // Use the referenced article to iterate thru System PATH to find the right path
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top