I'm trying to create an installer that restores a Database and I want to return the results from the cmd command sqlcmd -L
into a drop down select on a button click event.
Is there any possible way to achieve that without sending the output of the command into a file.txt
and read each line afterwards?
private void button1_Click(object sender, EventArgs e)
{
string command;
command = "sqlcmd -L " ;
try
{
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = false;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
//Get the result and populate the drop down
}
catch (Exception objException)
{
// Log the exception
}
}
Not sure if this is what you need, but the Process
class has a StandardOutput
property that allows you to get the data dumped to the standard output (usually the console) by the process. So after the process has finished (use proc.WaitForExit()
for that) you can just do:
string processOutput = proc.StandardOutput.ReadToEnd();
Then if you need to process each line separately, you can do:
var lines = processOutput.Split(
new[] {Environment.NewLine},
StringSplitOptions.RemoveEmptyEntries);
foreach(var line in lines) { ... }