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

Asked

Viewed 8,059 times

7

I have a program that launches a command of Prompt windows.

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

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

2 answers

6


  • Perfect @dcastro! " ipconfig > "Desktop Environment" ip.txt" so it is saved on my Desktop, but if Windows has it in English, it will not be saved. How can I put it to everyone?

  • @Donvitocorleone, you can use %userprofile%\Desktop which will be directed to the desktop, language independent. Note that %userprofile% is a Windows variable.

  • @Donvitocorleone You asked the same question earlier: http://answall.com/questions/65376/obtain-camio-do-desktop

  • No friend @dcastro... Previously it was to put in the code of C#, now it is to write in the Command Line...

  • It’s already working, I managed to find another way! Thank you all!

  • Friend @dcastro, this is copying everything online, cannot do paragraphs?

Show 1 more comment

6

You can do this using the class Process:

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 like this:

string saida = ExecutarCMD("ipconfig");
File.WriteAllText("NomeArquivo.txt", saida);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.