Reputation: 249
I have an issues with WorkingDirectory
, and it is not setting the desired path correctly. I wrote a simple hello world test program, a.out
, to try out WorkingDirectory
. And the directory hierarchy is such:
/home/cli2/test
/bin/Debug/netcoreapp2.1/subdir/
a.out
/obj
Program.cs
test.csproj
I have the following settings for the Process class
process.StartInfo.FileName = "a.out"
process.StartInfo.UseShellExecute = false;
process.StartInfo.WorkingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "/subdir/";
When I execute dotnet run
, I would get an error of:
Unhandled Exception: System.ComponentModel.Win32Exception: No such file or directory
The issue that confuses me is that if I move a.out
to the top directory such that:
/home/cli2/project
/bin/Debug/netcoreapp2.1/subdir/
/obj
Program.cs
test.csproj
a.out
While having the same StartInfo
settings, process.start()
executes the hello world program without error. Furthermore, if I change FileName = "ls"
with the original subdirectory hierarchy, it does print out a.out
. For that case the WorkingDirectory
is behaving as expected. So I do understand this discrepancy and why I cannot call a.out
in a different directory.
Also I have tried both absolute and relative path for WorkingDirectory
, neither works when I call a.out
.
Upvotes: 1
Views: 4161
Reputation: 183
The meaning of process.StartInfo.WorkingDirectory
in this case is not the location of the executable.
That is what's causing the behavior your are experiencing, and the meaning process.StartInfo.WorkingDirectory
changes based on the value of process.StartInfo.UseShellExecute
.
From the Microsoft documentation:
The WorkingDirectory property behaves differently when UseShellExecute is true than when UseShellExecute is false.
When UseShellExecute is false, the WorkingDirectory property is not used to find the executable. Instead, its value applies to the process that is started and only has meaning within the context of the new process.
The default value for UseShellExecute
in dotnet core is false
. I have experienced strange things when setting UseShellExecute
to true on Linux.
Personally, I would keep it false and make sure to use the full path or a path relative to the project root directory like this:
process.StartInfo.FileName="bin/Debug/netcoreapp2.1/subdir/a.out";
Upvotes: 5