Hello, I'm trying to get a return from an IF line of the Command Prompt (CMD) with Visual Studio 2015 in C #, but I'm not getting it.
The following code executes the CMD, inserts the directory path containing a C ++ (.cpp) file, and using the MinGW compiler, compiles and generates the executable (.exe) or error message occurs. Using IF EXIST, confirm whether the executable was created or not. But the return of the IF that indicates if the file was found or not found, not being able to return the result in which it will be used in a variable that will be validated in the future.using System;
using System.Windows.Forms;
using System.Diagnostics;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnExecutar_Click(object sender, EventArgs e)
{
string aspasDuplas = lblAspasDuplas.Text;
string retornar;
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe");
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.UseShellExecute = false;
processStartInfo.CreateNoWindow = true; // Não mostrar janela do cmd
Process process = Process.Start(processStartInfo);
process.StandardInput.WriteLine(@"cd C:\Users\Desktop\ConsoleApplication1\ConsoleApplication1");
process.StandardInput.WriteLine(@"g++ -o Source Source.cpp");
process.StandardInput.WriteLine(@"IF EXIST " + aspasDuplas + "Source.exe" + aspasDuplas + " (ECHO found) ELSE (ECHO not found)");
retornar = process.StandardOutput.ReadLine();
process.StandardInput.WriteLine(@"exit");
process.WaitForExit(); // espera o cmd.exe terminar
txtRetorno.Text = retornar;
}
}
}
But your Return text is Always:
Microsoft Windows [versÆo 10.0.16299.248]
Use the ReadToEnd command instead of ReadLine:
Process process = Process.Start(processStartInfo);
process.StandardInput.WriteLine(@"cd C:\Users\Desktop\ConsoleApplication1\ConsoleApplication1");
process.StandardInput.WriteLine(@"g++ -o Source Source.cpp");
process.StandardInput.WriteLine(@"IF EXIST " + aspasDuplas + "Source.exe" + aspasDuplas + " (ECHO found) ELSE (ECHO not found)");
process.StandardInput.WriteLine(@"exit");
retornar = process.StandardOutput.ReadToEnd();
process.WaitForExit(); // espera o cmd.exe terminar
txtRetorno.Text = retornar;
But your return is all CMD writing:
Microsoft Windows [versÆo 10.0.16299.248]
(c) 2017 Microsoft Corporation. Todos os direitos reservados.
C:\Users\Desktop\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug>cd C:\Users\Desktop\ConsoleApplication1\ConsoleApplication1
C:\Users\Desktop\ConsoleApplication1\ConsoleApplication1>g++ -o Source Source.cpp
C:\Users\Desktop\ConsoleApplication1\ConsoleApplication1>IF EXIST "Source.exe" (ECHO found) ELSE (ECHO not found)
not found
C:\Users\Desktop\ConsoleApplication1\ConsoleApplication1>exit
If someone can help me get only the IF return (found or not found). Thank you in advance for those who help.