문제

I can in C# do the following:

var pSpawn = new Process
     {
         StartInfo = { WorkingDirectory = @"C:\temp", FileName = fileToRun, CreateNoWindow = true }
     };
     pSpawn.Start();

and this works fine.... however I am wondering if there is a way to run a command (ie: "dir /b") without having to encapsulate it in a batch file?

도움이 되었습니까?

해결책

Just start the cmd.exe and pass the arguments required

 var pSpawn = new Process
 {
     StartInfo = 
     { 
         WorkingDirectory = @"C:\temp", 
         FileName = "cmd.exe", 
         Arguments ="/K dir /b" }
 };

 pSpawn.Start();

I have added the parameter /K to leave the command window open so, it is possible to see the output of the command dir.
Of course I think that you are really interested to catch the output of the command.
In this case you could work with something like this:

StringBuilder sb = new StringBuilder();
var pSpawn = new Process
{
     StartInfo = 
     { 
        WorkingDirectory = @"C:\temp", 
        FileName = "cmd.exe", 
        Arguments ="/c dir /b", 
        CreateNoWindow = true,
        RedirectStandardOutput = true,
        RedirectStandardInput = true,
        UseShellExecute = false
     }
};

pSpawn.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data);
pSpawn.Start();
pSpawn.BeginOutputReadLine();
pSpawn.WaitForExit();
Console.WriteLine(sb.ToString());

다른 팁

You can call something like this:

ProcessStartInfo info = new ProcessStartInfo("cmd.exe");
info.Arguments = "/c dir /b";
Process.Start(info);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top