Adding ProcessBuilder class
This way only this file has to use System.Diagnostics
This commit is contained in:
83
Password Manager/ProcessBuilder.cs
Normal file
83
Password Manager/ProcessBuilder.cs
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
|
||||||
|
namespace Password_Manager
|
||||||
|
{
|
||||||
|
public delegate void ProcessSuccess();
|
||||||
|
public delegate void ProcessFailure(Exception e);
|
||||||
|
static class ProcessBuilder
|
||||||
|
{
|
||||||
|
public ProcessSuccess? ProcessFinished;
|
||||||
|
public ProcessFailure? ProcessFailed;
|
||||||
|
|
||||||
|
public static void Run(string procName, string args)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Process.Start(procName, args);
|
||||||
|
ProcessFinished?.Invoke();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
ProcessFailed?.Invoke(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
ClearDelegate()
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ClearDelegate()
|
||||||
|
{
|
||||||
|
//clear delegate because static
|
||||||
|
if (ProcessFinished != null)
|
||||||
|
{
|
||||||
|
foreach (ProcessSuccess p in ProcessFinished)
|
||||||
|
{
|
||||||
|
ProcessFinished -= p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (ProcessFailed != null)
|
||||||
|
{
|
||||||
|
foreach (ProcessFailure p in ProcessFailed)
|
||||||
|
{
|
||||||
|
ProcessFailed -= p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string? GetOutput(string procName, string args)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Process proc = new Process()
|
||||||
|
{
|
||||||
|
StartInfo = new ProcessStartInfo
|
||||||
|
{
|
||||||
|
FileName = procName,
|
||||||
|
Arguments = args,
|
||||||
|
UseShellExecute = false,
|
||||||
|
RedirectStandardOutput = true;
|
||||||
|
CreateNoWindow = true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
proc.Start();
|
||||||
|
|
||||||
|
StringBuilder builder = new StringBuilder();
|
||||||
|
while (!proc.StandardOutput.EndOfStream)
|
||||||
|
{
|
||||||
|
builder.Append(proc.StandardOutput.ReadLine());
|
||||||
|
}
|
||||||
|
|
||||||
|
ProcessFinished?.Invoke();
|
||||||
|
return builder.ToString();
|
||||||
|
} catch (Exception e)
|
||||||
|
{
|
||||||
|
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
|
ProcessFailed.Invoke(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
ClearDelegate();
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user