Search code examples
c#processshortcutshellexecute

Programmatically setting startin location when starting a process


I have an application that creates a shortcut on my desktop and allows you to drag and drop files into the shortcut to perform an action (convert a word document to PDF). Now what I am trying to do is perform this action programmatically using shellexecute (.NET Process.Start()).

The problem is that it doesnt seem to be working and I have a sneaking suspicion this has something to do with the fact that the shortcut created has the "Start in" parameter set to a specific folder.

So it looks like this:

Shortcut target: "C:\Program Files (x86)\MyPDFConvertor\MyPDFConvertor.exe"
Shortcut startin: "C:\Program Files (x86)\MyPDFConvertor\SomeSubfolder\SomeSubSubFolder"

My code was the following.

System.Diagnostics.Process.Start("C:\\Program Files (x86)\\MyPDFConvertor\\MyPDFConvertor.exe", "C:\\MyFiles\\This is a test word document.docx");

Fundamentally my question boils down to: What does "Startin" actually mean/do for shortcuts and can I replicate this functionality when starting an application using either shellexecute or Process.Start?


Solution

  • As Yahia said, set the WorkingDirectory property. You also need to quote the arguments. Here is a rough example:

    //System.Diagnostics.Process.Start("C:\\Program Files (x86)\\MyPDFConvertor\\MyPDFConvertor.exe", "C:\\MyFiles\\This is a test word document.docx");
    ProcessStartInfo start = new ProcessStartInfo();
    //must exist, and be fully qualified:
    start.FileName = Path.GetFullPath("C:\\Program Files (x86)\\MyPDFConvertor\\MyPDFConvertor.exe");
    //set working directory:
    start.WorkingDirectory = Path.GetFullPath("C:\Program Files (x86)\MyPDFConvertor\SomeSubfolder\SomeSubSubFolder");
    //arguments must be quoted:
    const char quote = '"';
    start.Arguments = quote + "C:\\MyFiles\\This is a test word document.docx" + quote;
    //disable the error dialog
    start.ErrorDialog = false;
    try
    {
        Process process = Process.Start(start);
        if(process == null)
        {//started but we don't have access
    
        }
        else
        {
            process.WaitForExit();
            int exitCode = process.ExitCode;
        }
    }
    catch
    {
        Console.WriteLine("failed to start the program.");
    }