Eugene Lim
Eugene Lim

Reputation: 269

I'm having exception errors, file not found

When i try to run this function it keep crashing when the process starts.

public static void MapDestinationToSource (string destination, string source)
{
    System.Diagnostics.Process proc = new System.Diagnostics.Process ();
    // set the file to execute
    proc.StartInfo.FileName = "mklink";
    proc.StartInfo.Arguments = $"/D \"{source}\" \"{destination}\"";
    // Redirect the output stream of the child process.
    proc.StartInfo.UseShellExecute = true;
    //proc.StartInfo.RedirectStandardOutput = true;
    // start the process
    proc.Start ();
    // Do not wait for the child process to exit before
    // reading to the end of its redirected stream.
    // p.WaitForExit();
    // Read the output stream first and then wait.
    string output = proc.StandardOutput.ReadToEnd ();
    proc.WaitForExit ();
}

Exception:

System.ComponentModel.Win32Exception occurred
  HResult=0x80004005
  Message=The system cannot find the file specified
  Source=System
  StackTrace:
   at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
   at System.Diagnostics.Process.Start()
   at GameCloud.StorageLibrary.MapDestinationToSource(String destination, String source) in D:\Development\code\sample\server\ClientAgent\ClientAgent\StorageLibrary.cs:line 130
   at GameCloud.Program.Main(String[] args) in D:\Development\code\sample\server\ClientAgent\ClientAgent\Program.cs:line 135

When i execute the command on command line, it works. But it does not when in the code. I already set the security policies to allow the current user to execute the mklink command without elevated access.

Upvotes: 0

Views: 260

Answers (1)

mjwills
mjwills

Reputation: 23864

If you are trying to execute executable programs (bob.exe) check out my striked out answer below.

Since you are trying to run mklink which is built-in to cmd then you need to use:

proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = $"/C mklink /D \"{source}\" \"{destination}\"";

The docs state:

When UseShellExecute is true, the WorkingDirectory property specifies the location of the executable. If WorkingDirectory is an empty string, it is assumed that the current directory contains the executable.

and then:

When UseShellExecute is false, the FileName property can be either a fully qualified path to the executable, or a simple executable name that the system will attempt to find within folders specified by the PATH environment variable.

As such, you need to either set UseShellExecute to false (so that your PATH is used to find the executable) or set WorkingDirectory to the folder that contains the executable.

Upvotes: 2

Related Questions