2

I'm trying to run CMD from my code. This is the line that I run in my command line, and it works when I run it manually:

C:\Dev\MySite\web\Website\comparison-tool\data\ & node csvToJson.js

This is what I have in my code:

string commandText = String.Format("/C {0}{1} & node csvToJson.js", root, csvToJsonFolder);
Process.Start("CMD.exe", commandText);

commandText evaluates to /C C:\Dev\MySite\web\Website\comparison-tool\data\ & node csvToJson.js

It runs without error, but nothing seems to have happened. The command prompt doesn't open, so I can't see any errors that may have occurred. The command is supposed to result in a file being written to a particular folder, and when I run the command manually the file gets written, but when I run my code the file does not get written.

EDIT: I changed my code to this:

Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Normal;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = commandText;
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
process.StartInfo = startInfo;
process.Start();

string result = process.StandardOutput.ReadToEnd();

The result is just an empty string. There is no error message or anything.

Erica Stockwell-Alpert
  • 4,624
  • 10
  • 63
  • 130
  • I guess the command prompt gets each space-separated-string as an individual input. – Green Falcon Oct 19 '16 at 16:16
  • You can use `ProcessStartInfo` to tell it to redirect any output to `StreamReader` then you can read what the console said. [This CodeProject article](http://www.codeproject.com/Articles/25983/How-to-Execute-a-Command-in-C) has an example in the first section. Maybe if you can see the error you can debug further. – Equalsk Oct 19 '16 at 16:18
  • Maybe you try with ProcessStartInfo? Like second answer here http://stackoverflow.com/a/1469790/2202391 – Daniil Oct 19 '16 at 16:20
  • I tried that, and the StandardOutput is just an empty string – Erica Stockwell-Alpert Oct 19 '16 at 16:26

1 Answers1

0

The problem was in my command text, I forgot "cd". Should have been "/C cd C:\Dev\MySite\web\Website\comparison-tool\data\ & node csvToJson.js"

Erica Stockwell-Alpert
  • 4,624
  • 10
  • 63
  • 130
  • I just wanted to write this. You better use `/C cd /D C:\Dev\MySite\web\Website\comparison-tool\data\ & node.exe csvToJson.js` to make it work even if your C# application is executed from a drive different than drive C:. – Mofi Oct 19 '16 at 16:55