Run Windows Prompt commands and save the output to a text file

6

I have a program that launches a Windows Prompt command.

I want to copy the output of this command and save it to a text file.

Example: The command is ipconfig and I want the output to be copied to a file.

    
asked by anonymous 08.06.2015 / 10:50

2 answers

6

Use > to redirect output .

ipconfig > file.txt
    
08.06.2015 / 11:44
4

You can do this by using the Process class:

public static string ExecutarCMD(string comando)
{
    using (Process processo = new Process())
    {
        processo.StartInfo.FileName = Environment.GetEnvironmentVariable("comspec");

        // Formata a string para passar como argumento para o cmd.exe
        processo.StartInfo.Arguments = string.Format("/c {0}", comando);

        processo.StartInfo.RedirectStandardOutput = true;
        processo.StartInfo.UseShellExecute = false;
        processo.StartInfo.CreateNoWindow = true;

        processo.Start();
        processo.WaitForExit();

        string saida = processo.StandardOutput.ReadToEnd();
        return saida;
        }
    }

Note : Declare the namespaces System.Diagnostics and System.IO .

Use this:

string saida = ExecutarCMD("ipconfig");
File.WriteAllText("NomeArquivo.txt", saida);
    
08.06.2015 / 12:09