Skip to content

Instantly share code, notes, and snippets.

@lexnewgate
Created December 7, 2018 07:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lexnewgate/bdfe5e34057aa175f73a4377c397dcb5 to your computer and use it in GitHub Desktop.
Save lexnewgate/bdfe5e34057aa175f73a4377c397dcb5 to your computer and use it in GitHub Desktop.
UnityProcessHelper
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Debug = UnityEngine.Debug;
namespace Locality
{
class ProcessHelper
{
public static int RunWinCmd(string cmd)
{
string exe = "cmd.exe";
//cmd options /C Carries out the command specified by string and then terminates
string argus = $"/c {cmd}";
return Run(exe, argus);
}
public static int Run(string exe,string argus)
{
int exitCode;
ProcessStartInfo processInfo;
Process process= new Process();
processInfo = new ProcessStartInfo(exe, argus);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;//false to enable redirect io
// *** Redirect the output ***
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
process = Process.Start(processInfo);
List<string> outputList = new List<string>();
List<string> errorList = new List<string>();
process.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
outputList.Add(e.Data);
process.BeginOutputReadLine();
process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
errorList.Add(e.Data);
process.BeginErrorReadLine();
process.WaitForExit();
exitCode = process.ExitCode;
Debug.Log($"Exe:{exe} Argus:{argus}");
Debug.Log("ExitCode: " + exitCode.ToString() + " ExecuteCommand");
string errorInfo = string.Join("\n", errorList);
string logInfo = string.Join("\n", outputList);
if(!string.IsNullOrWhiteSpace(errorInfo))
{
Debug.LogError($"Error:\n {errorInfo}" );
}
if(!string.IsNullOrWhiteSpace(logInfo))
{
Debug.Log( $"Log:\n{logInfo}");
}
process.Close();
return exitCode;
}
public static void OpenFolder(string folderPath)
{
new DirectoryInfo(folderPath).Create();
Process.Start(folderPath);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment