I need to create app that runs different commands (PowerShell.exe, ipconfig, etc.), but when the ExecuteCommand is called the UI freezes until work is finished.
Tried to run the method using await proc.StandardOutput.ReadToEndAsync(), but is not working. (it hangs on the mentioned line and is not continuing on the next line)
What I’m doing wrong?
Thanks in advance.
ExecuteCommand:
public static async Task<string> ExecuteCommand(string command)
{
try
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardInput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit();
var message = proc.StandardOutput.ReadToEndAsync();
//var error = await proc.StandardError.ReadToEndAsync();
proc.Close();
//var errorContent = error;
return message.Result;
}
catch (Exception objException)
{
return objException.Message;
}
}
Logger:
public void Logger(string value)
{
logtxt.AppendText("[" + DateTime.Now + "]: " + value + Environment.NewLine);
logtxt.SelectionStart = logtxt.Text.Length;
logtxt.ScrollToCaret();
}
IsActive:
private async Task<bool> IsActive()
{
string text = await ExecuteCommand("PowerShell.exe -Command "Get-VPNconnection -AllUserConnection"");
Logger(text);
...more code...
}
Form1_Shown (I moved the below code from Form_Load, cause it takes time until the UI appears):
private void Form1_Shown(object sender, EventArgs e)
{
if (IsActive().Result)
{
...more code...
}
}