-1

I need to input the file location from OpenFileDialog, as an argument to a .exe file, the problem is the file name has spaces and when they are called by the exe file as arguments, it breaks up on the spaces. For example if I where to get "C:\Users\Target Files\singlefile.txt", the string would be split between "Target" and "File"

private static void CreateBinFromHex(String pathToHexFile)
{
    // Use ProcessStartInfo class
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.CreateNoWindow = false;
    startInfo.UseShellExecute = false;
    startInfo.FileName = System.IO.Directory.GetCurrentDirectory() + "\\hex2bin.exe";
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    startInfo.Arguments = pathToHexFile;

    try
    {
        // Start the process with the info we specified.
        // Call WaitForExit and then the using statement will close.
        using (Process exeProcess = Process.Start(startInfo))
        {
            exeProcess.WaitForExit();
        }
    }
    catch(SystemException e)
    {
        MessageBox.Show(e.Message);
    }
}

I tried different combinations in the terminal and found that enclosing the argument in a single quotes allows for a string including spaces to be used, but I cannot find a way to apply that in my program. For example---> the.exe 'C:\Users\Target Files\singlefile.txt' works perfectly.

Rand Random
  • 7,300
  • 10
  • 40
  • 88

1 Answers1

1

You can achieve the behavior you want with adding an extra double quotations (") for the string parameter (and escaping them):

pathToHexFile = "\"C:\\Users\\Target Files\\singlefile.txt\""

Or in your case when pathToHexFile is a parameter for the method:

pathToHexFile = "\"" + pathToHexFile + "\"";

This way the the process start will call your exe like this:

the.exe "C:\Users\Target Files\singlefile.txt"

And the double quotations will threat the string as a whole. As a comparison the single quotation (') will indeed split the string into two parameters.

Tested on .NET Framework 4.7.2

antanta
  • 618
  • 8
  • 16