Hi,
I have the following code to run a dos command e.g dir:
strCmdLine =
" /p";System.Diagnostics.Process.Start("dir", strCmdLine);
How du i recieve the putput from the dir command?
Hi,
I have the following code to run a dos command e.g dir:
strCmdLine =
" /p";How du i recieve the putput from the dir command?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
AlanRank #669 · 3.6K reputationPosted Sep 4, 2007, 7:38 AM EDT
Well, firstly, I don't think that code will work because 'dir' is a command within the command processor, cmd.exe, rather than an executable program in its own right.
Secondly, I wouldn't use the /p option as that will cause your program to hang waiting for a key press to display the next page of files.
Subject to that, this code should capture the whole output from the dir command and will also suppress the appearance of the command window in which it runs:
using System;
using System.IO;
using System.Diagnostics;
class Program
{
static void Main()
{
Process proc = new Process();
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.Arguments = @"/C dir";
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.Start();
StreamReader sr = new StreamReader(proc.StandardOutput.BaseStream);
string output = sr.ReadToEnd();
sr.Close();
proc.WaitForExit();
//if want to write output to file
string fileName = @"someFile.txt";
StreamWriter sw = new StreamWriter(fileName); // overwrites any existing file
sw.Write(output);
sw.Close();
}
}
MOrten Kruse3 reputationPosted Sep 5, 2007, 4:51 AM EDT
Hi,
This worked very fine for me.
It was not the dir command that i wsa using but I did provide that just for the meaning of the example.
Best regards,
Morten