0

I want to run simple CMD command and my argument contains spaces (" ").

In this case this is not working since its recognized as command with several arguments...

This is what I have tried (same results):

string arg = "c:\my path\ this is test\file.doc";

string.Format("\"{0}\"", arg)

Edit:

public void Invoke(string fileName, string arg)
{
    ProcessStartInfo processStartInfo = new ProcessStartInfo();
    processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    processStartInfo.FileName = fileName;
    if (arg != "")
        processStartInfo.Arguments = arg;
    processStartInfo.RedirectStandardOutput = true;
    processStartInfo.RedirectStandardError = true;
    processStartInfo.RedirectStandardInput = true;
    processStartInfo.UseShellExecute = false;
    processStartInfo.CreateNoWindow = true;

    Process process = new Process();
    process.StartInfo = processStartInfo;
    process.Exited += Process_Exited;
    process.EnableRaisingEvents = true;
    process.Start();
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();
}

Usage:

string arg = "c:\my path\this is my string.ps1";   
Invoke(@"C:\windows\system32\windowspowershell\v1.0\powershell.exe", string.Format("\"{0}\"", arg)); 
Axel
  • 3,331
  • 11
  • 35
  • 58
user979033
  • 5,430
  • 7
  • 32
  • 50
  • 1
    "not working since this recognized as command with several arguments" where is your code that is supposedly doing this? I don't see where you're using it....is this a console application:? Please show **all relevant code** – rory.ap Dec 16 '16 at 16:15
  • Quoting it is the correct way. How are you reading the arguments? See [here](http://stackoverflow.com/questions/18639663/how-to-pass-command-line-parameters-with-space-in-batch-file). Also fyi `string arg = "c:\ this is test\file.doc";` does not compile, you want `string arg = @"c:\ this is test\file.doc";` or `string arg = "c:\\ this is test\\file.doc";` – Quantic Dec 16 '16 at 16:16
  • please see my edit – user979033 Dec 16 '16 at 21:04
  • The title here is incorrect and misleading. What you're using is *not* the classic Windows Command Line tool *UNIVERSALLY* known as *CMD*. Please edit your title to *PowerShell* so that people don't waste their time here. Thanks. – Ricardo Sep 12 '22 at 17:03

2 Answers2

1

You can try this :

string arg = @"c:\\"my path\"\\"this is my string.ps1\"";   
Invoke(@"C:\windows\system32\windowspowershell\v1.0\powershell.exe", 
string.Format("\"{0}\"", arg));

or string arg = @"c:/\"my path\"/\"this is my string.ps1\"";

sifa vahora
  • 117
  • 11
0

Within your application join all the arguments together to get a single space separated argument like this:

var joinedArgs = string.Join(" ", args);

Then pass the joined args to your function.

Theo
  • 885
  • 6
  • 16