Search code examples
c#pythonpathspace

Problem with space in path, arguments C# to launch python script


I don't know how can I code the string format to keep the full path with space, because, it is split at each space. 4 arguments:

  • C:/MyDoc/Example/MyCSV File 1.csv
  • -1
  • 20-05-2019
  • 7

python.run_cmd("C:/MyCode.py", "C:/MyDoc/Example/MyCSV File 1.csv -1 20-05-2019 7");

Function:

 public static void run_cmd(string cmd, string args)
    {
        ProcessStartInfo start = new ProcessStartInfo();
        start.FileName = "C:/PRGM/python.exe";
        start.Arguments = string.Format("{0} {1}",cmd, args);
        start.UseShellExecute = false;
        start.RedirectStandardOutput = true;
        using (Process process = Process.Start(start))
        {
            using (StreamReader reader = process.StandardOutput)
            {
                string result = reader.ReadToEnd();
                Console.Write(result);
            }
        }
    }

Solution

  • How about wrapping the file name in quotes, you'll need to escape them using a backslash \:

    python.run_cmd("C:/MyCode.py", "\"C:/MyDoc/Example/MyCSV File 1.csv\" -1 20-05-2019 7");
    

    or using a verbatim string:

    python.run_cmd("C:/MyCode.py", @"""C:/MyDoc/Example/MyCSV File 1.csv"" -1 20-05-2019 7");