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.
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.
Use >
to redirect output .
ipconfig > file.txt
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);