Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process.start does not find file when useshellexecute = false

I need to call batch-files from my UWP Application. The way to do seems to be Process.Start(), but it says it does not find the file even tough it is definitly there when I follow the path it outputs. Filepath and Working Directory are both given as full paths as is requiered when using shellexecute = false.

It works when I set useshellexecute = true. Since the full path works here, the file is clearly there. With shellexecute = true the working directory only specifies where it should search for the file and the command prompt starts in the system32 directory, but I need the working directory to be where the opened batch is located.

Hence the ShellExecute = false.

I tried: 1. ShellExecute = true. It finds the file but the working directory is not set correctly. 2. Hardcoding the absolute path to a batch. Still not found. 3. Setting StartInfo.FileName instead of giving it via argument. 4. relative paths 5. Process.Start(Filename). Can't set Working Directory without StartInfo 6. Look at similar questions, but the answer is always what I already have (Use full path when shellexecute = false)

string executable = args[2];

string path = Assembly.GetExecutingAssembly().CodeBase;
string directory = Path.GetDirectoryName(path);

var startInfo = new ProcessStartInfo(directory + @"\Diagnose\_data\Updater\" + executable);

startInfo.UseShellExecute = false;
startInfo.WorkingDirectory = directory + @"\Diagnose\_data\Updater";

startInfo.RedirectStandardError = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;

Process.Start(startInfo);

It should find the file since there is a full, absolute path given and the file is defintily there, but it gives an file not found error.

like image 936
Mika Avatar asked Oct 15 '22 13:10

Mika


1 Answers

Use Assembly.Location instead of Application.CodeBase. Application.CodeBase returns the source location of the assembly as a URL, not a file path. Assemblies could be loaded from URLs or byte arrays and CodeBase reflects that. It returns something like :

file:///C:/TEMP/LINQPad6/_kighplqc/neuyub/LINQPadQuery.dll

The Windows shell can handle file URLs and translates them to actual file paths. The OS itself requires file paths though.

You should use Path.Combine instead of concatenating strings too, to avoid issues with extra or missing slashes. You should use something like :

string path = Assembly.GetExecutingAssembly().Location;
string directory = Path.GetDirectoryName(path);
var execPath=Path.Combine(directory,"Diagnose\_data\Updater",executable);

var startInfo = new ProcessStartInfo(execPath);
like image 98
Panagiotis Kanavos Avatar answered Oct 20 '22 15:10

Panagiotis Kanavos