From 13123b21038483e35db8bf4cfab973cd49390260 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miskolczi=20Rich=C3=A1rd?= Date: Wed, 29 Mar 2023 14:36:16 +0200 Subject: [PATCH] Adding ProcessBuilder class This way only this file has to use System.Diagnostics --- Password Manager/ProcessBuilder.cs | 83 ++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Password Manager/ProcessBuilder.cs diff --git a/Password Manager/ProcessBuilder.cs b/Password Manager/ProcessBuilder.cs new file mode 100644 index 0000000..661ad20 --- /dev/null +++ b/Password Manager/ProcessBuilder.cs @@ -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; + } + } +}