System.Diagnostics.Process.WaitForExit()

Here are the examples of the csharp api System.Diagnostics.Process.WaitForExit() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

2117 Examples 7

19 Source : GmicConfigDialog.cs
with GNU General Public License v3.0
from 0xC0000054

private void GmicThread()
        {
            DialogResult result = DialogResult.Cancel;

            try
            {
                List<GmicLayer> layers = new List<GmicLayer>();

                Surface clipboardSurface = null;
                try
                {
                    // Some G'MIC filters require the image to have more than one layer.
                    // Because use Paint.NET does not currently support Effect plug-ins accessing
                    // other layers in the doreplacedent, allowing the user to place the second layer on
                    // the clipboard is supported as a workaround.

                    clipboardSurface = Services.GetService<IClipboardService>().TryGetSurface();

                    if (clipboardSurface != null)
                    {
                        layers.Add(new GmicLayer(clipboardSurface, true));
                        clipboardSurface = null;
                    }
                }
                finally
                {
                    if (clipboardSurface != null)
                    {
                        clipboardSurface.Dispose();
                    }
                }

                layers.Add(new GmicLayer(EnvironmentParameters.SourceSurface, false));

                server.AddLayers(layers);

                server.Start();

                string arguments = string.Format(CultureInfo.InvariantCulture, ".PDN {0}", server.FullPipeName);

                using (Process process = new Process())
                {
                    process.StartInfo = new ProcessStartInfo(GmicPath, arguments);

                    process.Start();
                    process.WaitForExit();

                    if (process.ExitCode == GmicExitCode.Ok)
                    {
                        result = DialogResult.OK;
                    }
                    else
                    {
                        surface?.Dispose();
                        surface = null;

                        switch (process.ExitCode)
                        {
                            case GmicExitCode.ImageTooLargeForX86:
                                ShowErrorMessage(Resources.ImageTooLargeForX86);
                                break;
                        }
                    }
                }
            }
            catch (ArgumentException ex)
            {
                ShowErrorMessage(ex);
            }
            catch (ExternalException ex)
            {
                ShowErrorMessage(ex);
            }
            catch (IOException ex)
            {
                ShowErrorMessage(ex);
            }
            catch (UnauthorizedAccessException ex)
            {
                ShowErrorMessage(ex);
            }

            BeginInvoke(new Action<DialogResult>(GmicThreadFinished), result);
        }

19 Source : RawFileType.cs
with MIT License
from 0xC0000054

private static Doreplacedent GetRAWImageDoreplacedent(string file)
        {
            Doreplacedent doc = null;

            string options = GetDCRawOptions();
            // Set the -Z - option to tell the LibRaw dcraw-emu example program
            // that the image data should be written to standard output.
            string arguments = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0} -Z - \"{1}\"", options, file);
            ProcessStartInfo startInfo = new ProcessStartInfo(ExecutablePath, arguments)
            {
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true
            };
            bool useTIFF = options.Contains("-T");

            using (Process process = new Process())
            {
                process.StartInfo = startInfo;
                process.Start();

                if (useTIFF)
                {
                    using (Bitmap image = new Bitmap(process.StandardOutput.BaseStream))
                    {
                        doc = Doreplacedent.FromImage(image);
                    }
                }
                else
                {
                    using (PixMapReader reader = new PixMapReader(process.StandardOutput.BaseStream, leaveOpen: true))
                    {
                        doc = reader.DecodePNM();
                    }
                }

                process.WaitForExit();
            }

            return doc;
        }

19 Source : GmicEffect.cs
with GNU General Public License v3.0
from 0xC0000054

protected override void OnSetRenderInfo(EffectConfigToken parameters, RenderArgs dstArgs, RenderArgs srcArgs)
        {
            if (repeatEffect)
            {
                GmicConfigToken token = (GmicConfigToken)parameters;

                if (token.Surface != null)
                {
                    token.Surface.Dispose();
                    token.Surface = null;
                }

                if (File.Exists(GmicConfigDialog.GmicPath))
                {
                    try
                    {
                        using (GmicPipeServer server = new GmicPipeServer())
                        {
                            List<GmicLayer> layers = new List<GmicLayer>();

                            Surface clipboardSurface = null;
                            try
                            {
                                // Some G'MIC filters require the image to have more than one layer.
                                // Because use Paint.NET does not currently support Effect plug-ins accessing
                                // other layers in the doreplacedent, allowing the user to place the second layer on
                                // the clipboard is supported as a workaround.

                                clipboardSurface = Services.GetService<IClipboardService>().TryGetSurface();

                                if (clipboardSurface != null)
                                {
                                    layers.Add(new GmicLayer(clipboardSurface, true));
                                    clipboardSurface = null;
                                }
                            }
                            finally
                            {
                                if (clipboardSurface != null)
                                {
                                    clipboardSurface.Dispose();
                                }
                            }

                            layers.Add(new GmicLayer(EnvironmentParameters.SourceSurface, false));

                            server.AddLayers(layers);

                            server.Start();

                            string arguments = string.Format(CultureInfo.InvariantCulture, ".PDN {0} reapply", server.FullPipeName);

                            using (Process process = new Process())
                            {
                                process.StartInfo = new ProcessStartInfo(GmicConfigDialog.GmicPath, arguments);

                                process.Start();
                                process.WaitForExit();

                                if (process.ExitCode == GmicExitCode.Ok)
                                {
                                    OutputImageState state = server.OutputImageState;

                                    if (state.Error != null)
                                    {
                                        ShowErrorMessage(state.Error);
                                    }
                                    else
                                    {
                                        IReadOnlyList<Surface> outputImages = state.OutputImages;

                                        if (outputImages.Count > 1)
                                        {
                                            using (PlatformFolderBrowserDialog folderBrowserDialog = new PlatformFolderBrowserDialog())
                                            {
                                                folderBrowserDialog.ClreplacedicFolderBrowserDescription = Resources.ClreplacedicFolderBrowserDescription;
                                                folderBrowserDialog.VistaFolderBrowserreplacedle = Resources.VistaFolderBrowserreplacedle;

                                                if (!string.IsNullOrWhiteSpace(token.OutputFolder))
                                                {
                                                    folderBrowserDialog.SelectedPath = token.OutputFolder;
                                                }

                                                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                                                {
                                                    string outputFolder = folderBrowserDialog.SelectedPath;

                                                    try
                                                    {
                                                        OutputImageUtil.SaveAllToFolder(outputImages, outputFolder);
                                                    }
                                                    catch (ArgumentException ex)
                                                    {
                                                        ShowErrorMessage(ex);
                                                    }
                                                    catch (ExternalException ex)
                                                    {
                                                        ShowErrorMessage(ex);
                                                    }
                                                    catch (IOException ex)
                                                    {
                                                        ShowErrorMessage(ex);
                                                    }
                                                    catch (SecurityException ex)
                                                    {
                                                        ShowErrorMessage(ex);
                                                    }
                                                    catch (UnauthorizedAccessException ex)
                                                    {
                                                        ShowErrorMessage(ex);
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            Surface output = outputImages[0];

                                            if (output.Width == srcArgs.Surface.Width && output.Height == srcArgs.Surface.Height)
                                            {
                                                token.Surface = output.Clone();
                                            }
                                            else
                                            {
                                                // Place the full image on the clipboard when the size does not match the Paint.NET layer
                                                // and prompt the user to save it.
                                                // The resized image will not be copied to the Paint.NET canvas.
                                                Services.GetService<IClipboardService>().SetImage(output);

                                                using (PlatformFileSaveDialog resizedImageSaveDialog = new PlatformFileSaveDialog())
                                                {
                                                    resizedImageSaveDialog.Filter = Resources.ResizedImageSaveDialogFilter;
                                                    resizedImageSaveDialog.replacedle = Resources.ResizedImageSaveDialogreplacedle;
                                                    resizedImageSaveDialog.FileName = DateTime.Now.ToString("yyyyMMdd-THHmmss") + ".png";
                                                    if (resizedImageSaveDialog.ShowDialog() == DialogResult.OK)
                                                    {
                                                        string resizedImagePath = resizedImageSaveDialog.FileName;
                                                        try
                                                        {
                                                            using (Bitmap bitmap = output.CreateAliasedBitmap())
                                                            {
                                                                bitmap.Save(resizedImagePath, System.Drawing.Imaging.ImageFormat.Png);
                                                            }
                                                        }
                                                        catch (ArgumentException ex)
                                                        {
                                                            ShowErrorMessage(ex);
                                                        }
                                                        catch (ExternalException ex)
                                                        {
                                                            ShowErrorMessage(ex);
                                                        }
                                                        catch (IOException ex)
                                                        {
                                                            ShowErrorMessage(ex);
                                                        }
                                                        catch (SecurityException ex)
                                                        {
                                                            ShowErrorMessage(ex);
                                                        }
                                                        catch (UnauthorizedAccessException ex)
                                                        {
                                                            ShowErrorMessage(ex);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    switch (process.ExitCode)
                                    {
                                        case GmicExitCode.ImageTooLargeForX86:
                                            ShowErrorMessage(Resources.ImageTooLargeForX86);
                                            break;
                                    }
                                }
                            }
                        }
                    }
                    catch (ArgumentException ex)
                    {
                        ShowErrorMessage(ex);
                    }
                    catch (ExternalException ex)
                    {
                        ShowErrorMessage(ex);
                    }
                    catch (IOException ex)
                    {
                        ShowErrorMessage(ex);
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        ShowErrorMessage(ex);
                    }
                }
                else
                {
                    ShowErrorMessage(Resources.GmicNotFound);
                }
            }

            base.OnSetRenderInfo(parameters, dstArgs, srcArgs);
        }

19 Source : X86Assembly.cs
with MIT License
from 20chan

public static byte[] CompileToMachineCode(string asmcode)
        {
            var fullcode = $".intel_syntax noprefix\n_main:\n{asmcode}";
            var path = Path.Combine(Directory.GetCurrentDirectory(), "temp");
            var asmfile = $"{path}.s";
            var objfile = $"{path}.o";
            File.WriteAllText(asmfile, fullcode, new UTF8Encoding(false));
            var psi = new ProcessStartInfo("gcc", $"-m32 -c {asmfile} -o {objfile}")
            {
                RedirectStandardError = true,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };
            var gcc = Process.Start(psi);
            gcc.WaitForExit();
            if (gcc.ExitCode == 0)
            {
                psi.FileName = "objdump";
                psi.Arguments = $"-z -M intel -d {objfile}";
                var objdump = Process.Start(psi);
                objdump.WaitForExit();
                if (objdump.ExitCode == 0)
                {
                    var output = objdump.StandardOutput.ReadToEnd();
                    var matches = Regex.Matches(output, @"\b[a-fA-F0-9]{2}(?!.*:)\b");
                    var result = new List<byte>();
                    foreach (Match match in matches)
                    {
                        result.Add((byte)Convert.ToInt32(match.Value, 16));
                    }

                    return result.TakeWhile(b => b != 0x90).ToArray();
                }
            }
            else
            {
                var err = gcc.StandardError.ReadToEnd();
            }

            throw new ArgumentException();
        }

19 Source : Common.cs
with MIT License
from 1y0n

public static string Execute_Cmd(string cmd)
        {
            string output = "";
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动
            p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
            p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
            p.StartInfo.CreateNoWindow = true;//不显示程序窗口
            p.Start();//启动程序

            //向cmd窗口发送输入信息
            p.StandardInput.WriteLine(cmd + "&exit");

            p.StandardInput.AutoFlush = true;

            //获取cmd窗口的输出信息
            output = p.StandardOutput.ReadToEnd();

            p.WaitForExit();//等待程序执行完退出进程
            p.Close();
            return output;
        }

19 Source : Command.cs
with Apache License 2.0
from 214175590

public static CmdResult run(String cmd)
        {
            CmdResult result = new CmdResult();
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动
            p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
            p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
            p.StartInfo.CreateNoWindow = true;//不显示程序窗口
            p.Start();//启动程序

            //向cmd窗口发送输入信息
            p.StandardInput.WriteLine(cmd + "&exit");

            p.StandardInput.AutoFlush = true;
            //p.StandardInput.WriteLine("exit");
            //向标准输入写入要执行的命令。这里使用&是批处理命令的符号,表示前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死
            //同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令,后者表示必须前一个命令执行失败才会执行后面的命令

            //获取cmd窗口的输出信息
            result.result = p.StandardOutput.ReadToEnd();
            result.error = p.StandardError.ReadToEnd();

            p.WaitForExit();//等待程序执行完退出进程
            p.Close();

            return result;
        }

19 Source : SysProxyHandle.cs
with GNU General Public License v3.0
from 2dust

private static void ExecSysproxy(string arguments)
        {
            // using event to avoid hanging when redirect standard output/error
            // ref: https://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why
            // and http://blog.csdn.net/zhangweixing0/article/details/7356841
            using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
            using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
            {
                using (Process process = new Process())
                {
                    // Configure the process using the StartInfo properties.
                    process.StartInfo.FileName = Utils.GetTempPath("sysproxy.exe");
                    process.StartInfo.Arguments = arguments;
                    process.StartInfo.WorkingDirectory = Utils.GetTempPath();
                    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.RedirectStandardError = true;
                    process.StartInfo.RedirectStandardOutput = true;

                    // Need to provide encoding info, or output/error strings we got will be wrong.
                    process.StartInfo.StandardOutputEncoding = Encoding.Unicode;
                    process.StartInfo.StandardErrorEncoding = Encoding.Unicode;

                    process.StartInfo.CreateNoWindow = true;

                    StringBuilder output = new StringBuilder();
                    StringBuilder error = new StringBuilder();

                    process.OutputDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                        {
                            outputWaitHandle.Set();
                        }
                        else
                        {
                            output.AppendLine(e.Data);
                        }
                    };
                    process.ErrorDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                        {
                            errorWaitHandle.Set();
                        }
                        else
                        {
                            error.AppendLine(e.Data);
                        }
                    };
                    try
                    {
                        process.Start();

                        process.BeginErrorReadLine();
                        process.BeginOutputReadLine();

                        process.WaitForExit();
                    }
                    catch (System.ComponentModel.Win32Exception e)
                    {

                        // log the arguments
                        throw new Exception(process.StartInfo.Arguments);
                    }
                    string stderr = error.ToString();
                    string stdout = output.ToString();

                    int exitCode = process.ExitCode;
                    if (exitCode != (int)RET_ERRORS.RET_NO_ERROR)
                    {
                        throw new Exception(stderr);
                    }

                    //if (arguments == "query")
                    //{
                    //    if (stdout.IsNullOrWhiteSpace() || stdout.IsNullOrEmpty())
                    //    {
                    //        throw new Exception("failed to query wininet settings");
                    //    }
                    //    _queryStr = stdout;
                    //}
                }
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r

public static string ShellExecuteWithPath(string ShellCommand, string Path, string Username = "", string Domain = "", string Preplacedword = "")
        {

            if (ShellCommand == null || ShellCommand == "") return "";

            string ShellCommandName = ShellCommand.Split(' ')[0];
            string ShellCommandArguments = "";
            if (ShellCommand.Contains(" "))
            {
                ShellCommandArguments = ShellCommand.Replace(ShellCommandName + " ", "");
            }

            System.Diagnostics.Process shellProcess = new System.Diagnostics.Process();
            if (Username != "")
            {
                shellProcess.StartInfo.UserName = Username;
                shellProcess.StartInfo.Domain = Domain;
                System.Security.SecureString SecurePreplacedword = new System.Security.SecureString();
                foreach (char c in Preplacedword)
                {
                    SecurePreplacedword.AppendChar(c);
                }
                shellProcess.StartInfo.Preplacedword = SecurePreplacedword;
            }
            shellProcess.StartInfo.FileName = ShellCommandName;
            shellProcess.StartInfo.Arguments = ShellCommandArguments;
            shellProcess.StartInfo.WorkingDirectory = Path;
            shellProcess.StartInfo.UseShellExecute = false;
            shellProcess.StartInfo.CreateNoWindow = true;
            shellProcess.StartInfo.RedirectStandardOutput = true;
            shellProcess.StartInfo.RedirectStandardError = true;

            var output = new StringBuilder();
            shellProcess.OutputDataReceived += (sender, args) => { output.AppendLine(args.Data); };
            shellProcess.ErrorDataReceived += (sender, args) => { output.AppendLine(args.Data); };

            shellProcess.Start();

            shellProcess.BeginOutputReadLine();
            shellProcess.BeginErrorReadLine();
            shellProcess.WaitForExit();

            return output.ToString().TrimEnd();
        }

19 Source : Program.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r

public static string ShellExecuteWithPath(string ShellCommand, string Path, string Username = "", string Domain = "", string Preplacedword = "")
        {
            if (ShellCommand == null || ShellCommand == "") return "";

            string ShellCommandName = ShellCommand.Split(' ')[0];
            string ShellCommandArguments = "";
            if (ShellCommand.Contains(" "))
            {
                ShellCommandArguments = ShellCommand.Replace(ShellCommandName + " ", "");
            }

            System.Diagnostics.Process shellProcess = new System.Diagnostics.Process();
            if (Username != "")
            {
                shellProcess.StartInfo.UserName = Username;
                shellProcess.StartInfo.Domain = Domain;
                System.Security.SecureString SecurePreplacedword = new System.Security.SecureString();
                foreach (char c in Preplacedword)
                {
                    SecurePreplacedword.AppendChar(c);
                }
                shellProcess.StartInfo.Preplacedword = SecurePreplacedword;
            }
            shellProcess.StartInfo.FileName = ShellCommandName;
            shellProcess.StartInfo.Arguments = ShellCommandArguments;
            shellProcess.StartInfo.WorkingDirectory = Path;
            shellProcess.StartInfo.UseShellExecute = false;
            shellProcess.StartInfo.CreateNoWindow = true;
            shellProcess.StartInfo.RedirectStandardOutput = true;
            shellProcess.StartInfo.RedirectStandardError = true;

            var output = new StringBuilder();
            shellProcess.OutputDataReceived += (sender, args) => { output.AppendLine(args.Data); };
            shellProcess.ErrorDataReceived += (sender, args) => { output.AppendLine(args.Data); };

            shellProcess.Start();

            shellProcess.BeginOutputReadLine();
            shellProcess.BeginErrorReadLine();
            shellProcess.WaitForExit();

            return output.ToString().TrimEnd();
        }

19 Source : PointCloudToMeshComponentFull.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            int Downsample = 5000;
            int NormalsNeighbours = 100;
            bool debug = false;

            int maximumDeptOfReconstructionSurfaceTree = 8;
            int targetWidthOfTheFinestLevelOctree = 0;
            double ratioBetweenReconCubeAndBBCubeStd = 1.1;
            bool ReconstructorUsingLinearInterpolation = false;

            DA.GetData(1, ref Downsample);
            DA.GetData(2, ref NormalsNeighbours);
            DA.GetData(3, ref debug);
            DA.GetData(4, ref maximumDeptOfReconstructionSurfaceTree);
            DA.GetData(5, ref targetWidthOfTheFinestLevelOctree);
            DA.GetData(6, ref ratioBetweenReconCubeAndBBCubeStd);
            DA.GetData(7, ref ReconstructorUsingLinearInterpolation);

            //Guid to PointCloud
            //PointCloud c = new PointCloud();
            PointCloudGH c = new PointCloudGH();

            string debugInfo = debug ? "1" : "0";
            

            if (DA.GetData(0, ref c)) {
                if (!c.IsValid) return;
                if (c.Value.Count==0) return;
                Downsample = Math.Min(Downsample, c.Value.Count);

               // var watch = System.Diagnostics.Stopwatch.StartNew();
                // the code that you want to measure comes here

                /////////////////////////////////////////////////////////////////
                //Get Directory
                /////////////////////////////////////////////////////////////////
                string replacedemblyLocation = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
                string replacedemblyPath = System.IO.Path.GetDirectoryName(replacedemblyLocation);


                /////////////////////////////////////////////////////////////////
                //write PointCloud to PLY
                /////////////////////////////////////////////////////////////////
                PlyReaderWriter.PlyWriter.SavePLY(c.Value, replacedemblyPath + @"\in.ply");
                //Rhino.RhinoApp.WriteLine("PointCloudToMesh. Saved Input: " + replacedemblyPath + @"\in.ply");
                //watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());

                /////////////////////////////////////////////////////////////////
                //Ply to Mesh to Obj
                /////////////////////////////////////////////////////////////////
                //watch = System.Diagnostics.Stopwatch.StartNew();
                //tring argument = replacedemblyPath + "TestVisualizer.exe " + "-1 " + "100";//--asci 
                string argument = " "+Downsample.ToString()+ " " + NormalsNeighbours.ToString() + " " + debugInfo + " " + maximumDeptOfReconstructionSurfaceTree.ToString() + " " + targetWidthOfTheFinestLevelOctree.ToString() + " " + ratioBetweenReconCubeAndBBCubeStd.ToString() + " " + Convert.ToInt32(ReconstructorUsingLinearInterpolation).ToString();
                //--asci 
                                                                                                                  // Rhino.RhinoApp.WriteLine("PointCloudToMesh. Arguments: " + argument );



                // Rhino.RhinoApp.WriteLine("PointCloudToMesh. Directory: " + replacedemblyPath + @"\TestVisualizer.exe");

                if (debug) {
                    var proc = new System.Diagnostics.Process {
                        StartInfo = new System.Diagnostics.ProcessStartInfo {
                            FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
                            Arguments = argument,
                            //UseShellExecute = false,
                            //RedirectStandardOutput = true,
                            CreateNoWindow = false,
                            // WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                            WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
                        }
                    };

                    proc.Start();
                 
                    proc.WaitForExit();
                } else {
                    var proc = new System.Diagnostics.Process {
                        StartInfo = new System.Diagnostics.ProcessStartInfo {
                            FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
                            Arguments = argument,
                            //UseShellExecute = false,
                            //RedirectStandardOutput = true,
                            CreateNoWindow = true,
                             WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                            WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
                        }
                    };
                    proc.Start();
                    proc.WaitForExit();
                }

               // watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());

                /////////////////////////////////////////////////////////////////
                //Read Obj
                /////////////////////////////////////////////////////////////////
                ///

                //Outputs
               // watch = System.Diagnostics.Stopwatch.StartNew();

                // Initialize
                var obj = new ObjParser.Obj();

                // Read Wavefront OBJ file
                //obj.LoadObj(@"C:\libs\windows\out.obj");
            

                //PlyReaderWriter.PlyLoader plyLoader = new PlyReaderWriter.PlyLoader();
                //Mesh mesh3D = plyLoader.load(replacedemblyPath + @"\out.ply")[0];


                //Rhino.RhinoApp.WriteLine(replacedemblyPath + @"\windows\out.obj");
                obj.LoadObj(replacedemblyPath + @"\out.obj");

                Mesh mesh3D = new Mesh();
                foreach (ObjParser.Types.Vertex v in obj.VertexList) {
                    mesh3D.Vertices.Add(new Point3d(v.X, v.Y, v.Z));
                    mesh3D.VertexColors.Add(System.Drawing.Color.FromArgb((int)(v.r * 255), (int)(v.g * 255), (int)(v.b * 255)  ));
                }
 
                int num = checked(mesh3D.Vertices.Count - 1);

                foreach (ObjParser.Types.Face f in obj.FaceList) {

                    string[] lineData = f.ToString().Split(' ');
                    string[] v0 = lineData[1].Split('/');
                    string[] v1 = lineData[2].Split('/');
                    string[] v2 = lineData[3].Split('/');

                    MeshFace mf3D = new MeshFace(Convert.ToInt32(v0[0]) - 1, Convert.ToInt32(v1[0]) - 1, Convert.ToInt32(v2[0]) - 1);
                    if (mf3D.IsValid())
                        if (!(mf3D.A > num || mf3D.B > num || mf3D.C > num || mf3D.D > num))
                            mesh3D.Faces.AddFace(mf3D);


                }








                DA.SetData(0, mesh3D);

                /////////////////////////////////////////////////////////////////
                //Output Iso Values
                /////////////////////////////////////////////////////////////////
                string[] lines = System.IO.File.ReadAllLines(replacedemblyPath + @"\out.txt");
                double[] iso = new double[lines.Length];
                for (int i = 0; i < lines.Length; i++) { 
                    iso[i] = Convert.ToDouble(lines[i]);
                }
                //watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds/1000.0).ToString());

                DA.SetDataList(1, iso);

            }


        }

19 Source : PointCloudToMeshComponent.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            int Downsample = 5000;
            int NormalsNeighbours = 100;
            bool debug = false;

            DA.GetData(1, ref Downsample);
            DA.GetData(2, ref NormalsNeighbours);
            DA.GetData(3, ref debug);


            //Guid to PointCloud
            //PointCloud c = new PointCloud();
            PointCloudGH c = new PointCloudGH();

            string debugInfo = debug ? "1" : "0";
            

            if (DA.GetData(0, ref c)) {
                if (!c.IsValid) return;
                if (c.Value.Count == 0) return;
                Downsample = Math.Min(Downsample, c.Value.Count);

               // var watch = System.Diagnostics.Stopwatch.StartNew();
                // the code that you want to measure comes here

                /////////////////////////////////////////////////////////////////
                //Get Directory
                /////////////////////////////////////////////////////////////////
                string replacedemblyLocation = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
                string replacedemblyPath = System.IO.Path.GetDirectoryName(replacedemblyLocation);


                /////////////////////////////////////////////////////////////////
                //write PointCloud to PLY
                /////////////////////////////////////////////////////////////////
                PlyReaderWriter.PlyWriter.SavePLY(c.Value, replacedemblyPath + @"\in.ply");
                //Rhino.RhinoApp.WriteLine("PointCloudToMesh. Saved Input: " + replacedemblyPath + @"\in.ply");
                //watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());

                /////////////////////////////////////////////////////////////////
                //Ply to Mesh to Obj
                /////////////////////////////////////////////////////////////////
                //watch = System.Diagnostics.Stopwatch.StartNew();
                //tring argument = replacedemblyPath + "TestVisualizer.exe " + "-1 " + "100";//--asci 
                string argument = " "+Downsample.ToString()+ " " + NormalsNeighbours.ToString() + " " + debugInfo + " 8 0 1.1 0";//--asci 
                                                                                                                  // Rhino.RhinoApp.WriteLine("PointCloudToMesh. Arguments: " + argument );

      
                //int maximumDeptOfReconstructionSurfaceTree = atoi(argv[4]);//8
                //int targetWidthOfTheFinestLevelOctree = atoi(argv[5]);//0
                //float ratioBetweenReconCubeAndBBCubeStd = atof(argv[6]);    // 1.1
                //bool ReconstructorUsingLinearInterpolation = atoi(argv[7]) == 1;//0


                // Rhino.RhinoApp.WriteLine("PointCloudToMesh. Directory: " + replacedemblyPath + @"\TestVisualizer.exe");

                if (debug) {
                    var proc = new System.Diagnostics.Process {
                        StartInfo = new System.Diagnostics.ProcessStartInfo {
                            FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
                            Arguments = argument,
                            //UseShellExecute = false,
                            //RedirectStandardOutput = true,
                            CreateNoWindow = false,
                            // WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                            WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
                        }
                    };

                    proc.Start();
                 
                    proc.WaitForExit();
                } else {
                    var proc = new System.Diagnostics.Process {
                        StartInfo = new System.Diagnostics.ProcessStartInfo {
                            FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
                            Arguments = argument,
                            //UseShellExecute = false,
                            //RedirectStandardOutput = true,
                            CreateNoWindow = true,
                             WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                            WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
                        }
                    };
                    proc.Start();
                    proc.WaitForExit();
                }

               // watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());

                /////////////////////////////////////////////////////////////////
                //Read Obj
                /////////////////////////////////////////////////////////////////
                ///

                //Outputs
               // watch = System.Diagnostics.Stopwatch.StartNew();

                // Initialize
                var obj = new ObjParser.Obj();

                // Read Wavefront OBJ file
                //obj.LoadObj(@"C:\libs\windows\out.obj");
            

                //PlyReaderWriter.PlyLoader plyLoader = new PlyReaderWriter.PlyLoader();
                //Mesh mesh3D = plyLoader.load(replacedemblyPath + @"\out.ply")[0];


                //Rhino.RhinoApp.WriteLine(replacedemblyPath + @"\windows\out.obj");
                obj.LoadObj(replacedemblyPath + @"\out.obj");

                Mesh mesh3D = new Mesh();
                foreach (ObjParser.Types.Vertex v in obj.VertexList) {
                    mesh3D.Vertices.Add(new Point3d(v.X, v.Y, v.Z));
                    mesh3D.VertexColors.Add(System.Drawing.Color.FromArgb((int)(v.r * 255), (int)(v.g * 255), (int)(v.b * 255)  ));
                }
 
                int num = checked(mesh3D.Vertices.Count - 1);

                foreach (ObjParser.Types.Face f in obj.FaceList) {

                    string[] lineData = f.ToString().Split(' ');
                    string[] v0 = lineData[1].Split('/');
                    string[] v1 = lineData[2].Split('/');
                    string[] v2 = lineData[3].Split('/');

                    MeshFace mf3D = new MeshFace(Convert.ToInt32(v0[0]) - 1, Convert.ToInt32(v1[0]) - 1, Convert.ToInt32(v2[0]) - 1);
                    if (mf3D.IsValid())
                        if (!(mf3D.A > num || mf3D.B > num || mf3D.C > num || mf3D.D > num))
                            mesh3D.Faces.AddFace(mf3D);


                }








                DA.SetData(0, mesh3D);

                /////////////////////////////////////////////////////////////////
                //Output Iso Values
                /////////////////////////////////////////////////////////////////
                string[] lines = System.IO.File.ReadAllLines(replacedemblyPath + @"\out.txt");
                double[] iso = new double[lines.Length];
                for (int i = 0; i < lines.Length; i++) { 
                    iso[i] = Convert.ToDouble(lines[i]);
                }
                //watch.Stop();
                //Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds/1000.0).ToString());

                DA.SetDataList(1, iso);

            }


        }

19 Source : PlantumlSession.cs
with MIT License
from 8T4

internal void Execute(string path, bool processWholeDirectory)
        {
            var directory = processWholeDirectory
                ? path
                : new FileInfo(path)?.Directory?.FullName;

            try
            {
                if (string.IsNullOrEmpty(directory))
                {
                    throw new PlantumlException($"{nameof(PlantumlException)}: puml file not found.");
                }

                var results = new StringBuilder();

                var jar = StandardLibraryBaseUrl
                    ? $"-jar {FilePath} -verbose -o \"{directory}\" -charset UTF-8"
                    : $"-jar {FilePath} -DRELATIVE_INCLUDE=\".\" -verbose -o \"{directory}\" -charset UTF-8";

                ProcessInfo.Arguments = $"{jar} {path}";
                ProcessInfo.RedirectStandardOutput = true;
                ProcessInfo.StandardOutputEncoding = Encoding.UTF8;

                var process = new Process { StartInfo = ProcessInfo };

                process.OutputDataReceived += (_, args) => { results.AppendLine(args.Data); };

                process.Start();
                process.WaitForExit();
            }
            catch (Exception e)
            {
                throw new PlantumlException($"{nameof(PlantumlException)}: puml file not found.", e);
            }
        }

19 Source : compiler.cs
with MIT License
from aaaddress1

public static bool geneateAsmSource(string srcPath, string outAsmPath)
        {
            Process p = new Process();
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.FileName = Path.Combine(Properties.Settings.Default.gwPath, "g++.exe");
            p.StartInfo.WorkingDirectory = Properties.Settings.Default.gwPath;

            p.StartInfo.Arguments = string.Format("-S {0} -masm=intel {2} -o {1}", srcPath, outAsmPath, Properties.Settings.Default.clArg);
            p.Start();

            string errr = p.StandardError.ReadToEnd();
            string oupt = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
            if (File.Exists(outAsmPath)) return true;

            Program.mainUi.Invoke((MethodInvoker)delegate ()
            {
                if (logText == null) return;
                logMsg("============= Error =============", Color.Red);
                logMsg(errr + oupt, Color.Red);
            });
            return false;
        }

19 Source : compiler.cs
with MIT License
from aaaddress1

public static bool generateExe(string asmPath, string exeOutPath)
        {
            Process p = new Process();
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.FileName = Path.Combine(Properties.Settings.Default.gwPath, "g++.exe");
            p.StartInfo.WorkingDirectory = Properties.Settings.Default.gwPath;
            p.StartInfo.Arguments = string.Format("{0} -masm=intel {2} -o {1}", asmPath, exeOutPath, Properties.Settings.Default.linkArg);
            p.Start();

            string errr = p.StandardError.ReadToEnd();
            string oupt = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
            if (File.Exists(exeOutPath)) return true;

            Program.mainUi.Invoke((MethodInvoker)delegate ()
            {
                if (logText == null) return;
                logMsg("============= Error =============", Color.Red);
                logMsg(errr + oupt, Color.Red);
            });
            return false;
        }

19 Source : OVRADBTool.cs
with MIT License
from absurd-joy

public int RunCommand(string[] arguments, WaitingProcessToExitCallback waitingProcessToExitCallback, out string outputString, out string errorString)
	{
		int exitCode = -1;

		if (!isReady)
		{
			Debug.LogWarning("OVRADBTool not ready");
			outputString = string.Empty;
			errorString = "OVRADBTool not ready";
			return exitCode;
		}

		string args = string.Join(" ", arguments);

		ProcessStartInfo startInfo = new ProcessStartInfo(adbPath, args);
		startInfo.WorkingDirectory = androidSdkRoot;
		startInfo.CreateNoWindow = true;
		startInfo.UseShellExecute = false;
		startInfo.WindowStyle = ProcessWindowStyle.Hidden;
		startInfo.RedirectStandardOutput = true;
		startInfo.RedirectStandardError = true;

		outputStringBuilder = new StringBuilder("");
		errorStringBuilder = new StringBuilder("");

		Process process = Process.Start(startInfo);
		process.OutputDataReceived += new DataReceivedEventHandler(OutputDataReceivedHandler);
		process.ErrorDataReceived += new DataReceivedEventHandler(ErrorDataReceivedHandler);

		process.BeginOutputReadLine();
		process.BeginErrorReadLine();

		try
		{
			do
			{
				if (waitingProcessToExitCallback != null)
				{
					waitingProcessToExitCallback();
				}
			} while (!process.WaitForExit(100));

			process.WaitForExit();
		}
		catch (Exception e)
		{
			Debug.LogWarningFormat("[OVRADBTool.RunCommand] exception {0}", e.Message);
		}

		exitCode = process.ExitCode;

		process.Close();

		outputString = outputStringBuilder.ToString();
		errorString = errorStringBuilder.ToString();

		outputStringBuilder = null;
		errorStringBuilder = null;

		if (!string.IsNullOrEmpty(errorString))
		{
			if (errorString.Contains("Warning"))
			{
				UnityEngine.Debug.LogWarning("OVRADBTool " + errorString);
			}
			else
			{
				UnityEngine.Debug.LogError("OVRADBTool " + errorString);
			}
		}

		return exitCode;
	}

19 Source : OVRPlatformTool.cs
with MIT License
from absurd-joy

static void LoadRedistPackages(string dataPath)
		{
			// Check / Download the platform util and call list-redists on it
			activeProcess = true;
			string platformUtilPath = CheckForPlatformUtil(dataPath);
			InitializePlatformUtilProcess(platformUtilPath, "list-redists");

			OVRPlatformTool.log += "Loading redistributable packages...\n";

			List<RedistPackage> redistPacks = new List<RedistPackage>();

			ovrPlatUtilProcess.Exited += new EventHandler(
				(s, e) =>
				{
					activeProcess = false;
				}
			);

			ovrPlatUtilProcess.OutputDataReceived += new DataReceivedEventHandler(
				(s, e) =>
				{
					if (e.Data != null && e.Data.Length != 0 && !e.Data.Contains("\u001b") && !e.Data.Contains("ID"))
					{
						// Get the name / ID pair from the CLI and create a redist package instance
						string[] terms = e.Data.Split('|');
						if (terms.Length == 2)
						{
							RedistPackage redistPack = new RedistPackage(terms[1], terms[0]);
							redistPacks.Add(redistPack);
						}
					}
				}
			);

			try
			{
				ovrPlatUtilProcess.Start();
				ovrPlatUtilProcess.BeginOutputReadLine();

				ovrPlatUtilProcess.WaitForExit();

				if (redistPacks.Count != OVRPlatformToolSettings.RiftRedistPackages.Count)
				{
					OVRPlatformTool.log += "Successfully updated redistributable packages.\n";
					OVRPlatformToolSettings.RiftRedistPackages = redistPacks;
				}
				else
				{
					OVRPlatformTool.log += "Redistributable packages up to date.\n";
				}
			}
			catch
			{
				if (ThrowPlatformUtilStartupError(platformUtilPath))
				{
					LoadRedistPackages(dataPath);
				}
			}
		}

19 Source : TippingManager.cs
with MIT License
from acid-chicken

public static async Task<string> InvokeMethodAsync(params object[] args)
        {
            using (var process = Process.Start(new ProcessStartInfo("bitzeny-cli", string.Join(' ', args.Select(x => x == null || x is bool || x is sbyte || x is byte || x is short || x is ushort || x is int || x is uint || x is long || x is ulong || x is float || x is double || x is decimal ? x.ToString() : $"\"{x}\"")))
            {
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            }))
            using (var reader = process.StandardOutput)
            {
                var output = await reader.ReadToEndAsync().ConfigureAwait(false);
                process.WaitForExit();
                process.Close();
                return output.Trim();
            }
        }

19 Source : RunnerService.cs
with MIT License
from actions

protected override void OnStart(string[] args)
        {
            RunningLoop = Task.Run(
                () =>
                    {
                        try
                        {
                            bool stopping;
                            WriteInfo("Starting Actions Runner Service");
                            TimeSpan timeBetweenRetries = TimeSpan.FromSeconds(5);

                            lock (ServiceLock)
                            {
                                stopping = Stopping;
                            }

                            while (!stopping)
                            {
                                WriteInfo("Starting Actions Runner listener");
                                lock (ServiceLock)
                                {
                                    RunnerListener = CreateRunnerListener();
                                    RunnerListener.OutputDataReceived += RunnerListener_OutputDataReceived;
                                    RunnerListener.ErrorDataReceived += RunnerListener_ErrorDataReceived;
                                    RunnerListener.Start();
                                    RunnerListener.BeginOutputReadLine();
                                    RunnerListener.BeginErrorReadLine();
                                }

                                RunnerListener.WaitForExit();
                                int exitCode = RunnerListener.ExitCode;

                                // exit code 0 and 1 need stop service
                                // exit code 2 and 3 need restart runner
                                switch (exitCode)
                                {
                                    case 0:
                                        Stopping = true;
                                        WriteInfo(Resource.RunnerExitWithoutError);
                                        break;
                                    case 1:
                                        Stopping = true;
                                        WriteInfo(Resource.RunnerExitWithTerminatedError);
                                        break;
                                    case 2:
                                        WriteInfo(Resource.RunnerExitWithError);
                                        break;
                                    case 3:
                                        WriteInfo(Resource.RunnerUpdateInProcess);
                                        var updateResult = HandleRunnerUpdate();
                                        if (updateResult == RunnerUpdateResult.Succeed)
                                        {
                                            WriteInfo(Resource.RunnerUpdateSucceed);
                                        }
                                        else if (updateResult == RunnerUpdateResult.Failed)
                                        {
                                            WriteInfo(Resource.RunnerUpdateFailed);
                                            Stopping = true;
                                        }
                                        else if (updateResult == RunnerUpdateResult.SucceedNeedRestart)
                                        {
                                            WriteInfo(Resource.RunnerUpdateRestartNeeded);
                                            _restart = true;
                                            ExitCode = int.MaxValue;
                                            Stop();
                                        }
                                        break;
                                    default:
                                        WriteInfo(Resource.RunnerExitWithUndefinedReturnCode);
                                        break;
                                }

                                if (Stopping)
                                {
                                    ExitCode = exitCode;
                                    Stop();
                                }
                                else
                                {
                                    // wait for few seconds before restarting the process
                                    Thread.Sleep(timeBetweenRetries);
                                }

                                lock (ServiceLock)
                                {
                                    RunnerListener.OutputDataReceived -= RunnerListener_OutputDataReceived;
                                    RunnerListener.ErrorDataReceived -= RunnerListener_ErrorDataReceived;
                                    RunnerListener.Dispose();
                                    RunnerListener = null;
                                    stopping = Stopping;
                                }
                            }
                        }
                        catch (Exception exception)
                        {
                            WriteException(exception);
                            ExitCode = 99;
                            Stop();
                        }
                    });
        }

19 Source : CLangCompiler.cs
with MIT License
from adamant

public int Compile(
            ICompilerOutput output,
            string[] sourceFiles,
            string[] headerSearchPaths,
            string outputPath)
        {
            // used to have: -Wno-incompatible-pointer-types
            var options = "-std=c11 -fsanitize=undefined -fsanitize=integer -fsanitize=nullability -Wall -Wno-unused-label";
            // Next thing is needed for windows
            options += " -Xclang -flto-visibility-public-std";
            if (Path.GetExtension(outputPath) == ".dll") // TODO take this as an argument or something
                options += " --shared";
            var sources = string.Join(' ', sourceFiles);
            var headers = string.Join(' ', headerSearchPaths.Select(h => "--include-directory " + h));
            var arguments = $"{sources} -o {outputPath} {headers} {options}";
            output.WriteLine("clang arguments:");
            output.WriteLine(arguments);
            var startInfo = new ProcessStartInfo("clang", arguments)
            {
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true,
                UseShellExecute = false,
            };
            var process = new Process() { StartInfo = startInfo };
            // To prevent blocking on a full buffer, we have to process output as it happens
            process.OutputDataReceived += ProcessOutput;
            process.ErrorDataReceived += ProcessOutput;
            output.WriteLine("clang output:");
            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            process.WaitForExit();
            return process.ExitCode;

            void ProcessOutput(object s, DataReceivedEventArgs e)
            {
                output.WriteLine(e.Data);
            }
        }

19 Source : ConformanceTests.cs
with MIT License
from adamant

[Theory]
        [MemberData(nameof(GetConformanceTestCases))]
        public void Test_cases(TestCase testCase)
        {
            // Setup
            var codeFile = CodeFile.Load(testCase.FullCodePath);
            var code = codeFile.Code.Text;
            var compiler = new AdamantCompiler()
            {
                SaveLivenessreplacedysis = true,
                SaveReachabilityGraphs = true,
            };
            var references = new Dictionary<Name, PackageIL>();

            // Reference Standard Library
            var stdLibPackage = CompileStdLib(compiler);
            references.Add("adamant.stdlib", stdLibPackage);

            try
            {
                // replacedyze
                var package = compiler.CompilePackage("testPackage", codeFile.Yield(),
                    references.ToFixedDictionary());

                // Check for compiler errors
                replacedert.NotNull(package.Diagnostics);
                var diagnostics = package.Diagnostics;
                var errorDiagnostics = CheckErrorsExpected(testCase, codeFile, code, diagnostics);

                // Disreplacedemble
                var ilreplacedembler = new ILreplacedembler();
                testOutput.WriteLine(ilreplacedembler.Disreplacedemble(package));

                // We got only expected errors, but need to not go on to emit code
                if (errorDiagnostics.Any())
                    return;

                // Emit Code
                var codePath = Path.ChangeExtension(testCase.FullCodePath, "c");
                EmitCode(package, stdLibPackage, codePath);

                // Compile Code to Executable
                var exePath = CompileToExecutable(codePath);

                // Execute and check results
                var process = Execute(exePath);

                process.WaitForExit();
                var stdout = process.StandardOutput.ReadToEnd();
                testOutput.WriteLine("stdout:");
                testOutput.WriteLine(stdout);
                replacedert.Equal(ExpectedOutput(code, "stdout", testCase.FullCodePath), stdout);
                var stderr = process.StandardError.ReadToEnd();
                testOutput.WriteLine("stderr:");
                testOutput.WriteLine(stderr);
                replacedert.Equal(ExpectedOutput(code, "stderr", testCase.FullCodePath), stderr);
                replacedert.Equal(ExpectedExitCode(code), process.ExitCode);
            }
            catch (FatalCompilationErrorException ex)
            {
                var diagnostics = ex.Diagnostics;
                CheckErrorsExpected(testCase, codeFile, code, diagnostics);
            }
        }

19 Source : ProcessExtensions.cs
with Apache License 2.0
from adamralph

public static void Run(this Process process, bool noEcho, string echoPrefix, CancellationToken cancellationToken)
        {
            var cancelled = 0L;

            if (!noEcho)
            {
                Console.Out.WriteLine(process.GetMessage(echoPrefix));
            }

            _ = process.Start();

            using (cancellationToken.Register(
                () =>
                {
                    if (process.TryKill())
                    {
                        _ = Interlocked.Increment(ref cancelled);
                    }
                },
                useSynchronizationContext: false))
            {
                process.WaitForExit();
            }

            if (Interlocked.Read(ref cancelled) == 1)
            {
                cancellationToken.ThrowIfCancellationRequested();
            }
        }

19 Source : ClonesManager.cs
with MIT License
from adrenak

private static void ExecuteBashCommand(string command)
        {
            command = command.Replace("\"", "\"\"");

            var proc = new Process()
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "/bin/bash",
                    Arguments = "-c \"" + command + "\"",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                }
            };

            using (proc)
            {
                proc.Start();
                proc.WaitForExit();

                if (!proc.StandardError.EndOfStream)
                {
                    UnityEngine.Debug.LogError(proc.StandardError.ReadToEnd());
                }
            }
        }

19 Source : ThemeHandler.cs
with MIT License
from adrianmteo

public static void ChangeTheme(string path)
        {
            if (!File.Exists(path))
            {
                Logger.Error("Theme file does not exist at '{0}'", path);
                return;
            }

            string themeToolPath = @"ThemeTool.exe";

            if (!File.Exists(themeToolPath))
            {
                Logger.Error("'ThemeTool.exe' does not exist");
                return;
            }

            Logger.Debug("Running 'ThemeTool.exe' with theme '{0}'", path);

            try
            {
                ProcessStartInfo processInfo = new ProcessStartInfo
                {
                    FileName = themeToolPath,
                    Arguments = $"ChangeTheme \"{path}\"",
                    WindowStyle = ProcessWindowStyle.Hidden
                };

                Process process = Process.Start(processInfo);
                process.WaitForExit();

                Logger.Info("'ThemeTool.exe' exited with status code {0}", process.ExitCode);
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
            }
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void extractnsp()
        {
            offbtn();

            string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";
            Directory.CreateDirectory(tmpdir);

            statuslabel.Content = "Extracting NSP Container...";

            string hctdir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
            string arg = @"-tpfs0 --pfs0dir=tmp " + "\"" + inputdisplay.Text + "\"";

            Process hct = new Process();
            hct.StartInfo.FileName = hctdir;
            hct.StartInfo.Arguments = arg;
            hct.StartInfo.CreateNoWindow = true;
            hct.StartInfo.UseShellExecute = false;
            hct.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            hct.EnableRaisingEvents = true;

            hct.Start();

            startbar();

            await Task.Run(() => hct.WaitForExit());

            hct.Close();

            readxml();
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void reextractnsp()
        {
            offbtn();

            startbar();

            string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";
            Directory.CreateDirectory(tmpdir);

            statuslabel.Content = "Extracting NSP Container...";

            string hctdir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
            string arg = @"-tpfs0 --pfs0dir=tmp " + "\"" + inputdisplay.Text + "\"";

            Process hct = new Process();
            hct.StartInfo.FileName = hctdir;
            hct.StartInfo.Arguments = arg;
            hct.StartInfo.CreateNoWindow = true;
            hct.StartInfo.UseShellExecute = false;
            hct.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            hct.EnableRaisingEvents = true;

            hct.Start();

            await Task.Run(() => hct.WaitForExit());

            hct.Close();

            decryptbsgnca();
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void decryptbsgnca()
        {
            offbtn();

            startbar();

            statuslabel.Content = "Decrypting Base Game NCA...";

            string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";

            var di = new DirectoryInfo(tmpdir);
            var result = di.GetFiles().OrderByDescending(x => x.Length).Take(1).ToList();
            var larbnca = di.GetFiles().OrderByDescending(x => x.Length).Take(1).Select(x => x.FullName).ToList();

            string basenca = String.Join(" ", larbnca);

            string nspddir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
            string replacedlkeyp = bsgreplacedlkyinput.Text;
            string bsgtk = new string(replacedlkeyp.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray());
            string arg1 = @"-k keys.txt " + "--replacedlekey=" + bsgtk + " " + basenca;
            string arg2 = " --plaintext=" + tmpdir + "\\NCAID_PLAIN.nca";
            string arg = arg1 + arg2;
          
            Process decrnca = new Process();
            decrnca.StartInfo.FileName = nspddir;
            decrnca.StartInfo.Arguments = arg;
            decrnca.StartInfo.CreateNoWindow = true;
            decrnca.StartInfo.UseShellExecute = false;
            decrnca.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            decrnca.EnableRaisingEvents = true;

            decrnca.Start();

            await Task.Run(() => decrnca.WaitForExit());

            decrnca.Close();

            extractncau();
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void extractncau()
        {
            string updir = AppDomain.CurrentDomain.BaseDirectory + "\\upd";
            Directory.CreateDirectory(updir);

            statuslabel.Content = "Extracting Update NCA's...";

            string hctdir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
            string arg = @"-tpfs0 --pfs0dir=upd " + "\"" + upnspinputdisplay.Text + "\"";

            Process hct = new Process();
            hct.StartInfo.FileName = hctdir;
            hct.StartInfo.Arguments = arg;
            hct.StartInfo.CreateNoWindow = true;
            hct.StartInfo.UseShellExecute = false;
            hct.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            hct.EnableRaisingEvents = true;

            hct.Start();

            await Task.Run(() => hct.WaitForExit());

            hct.Close();

            applyupdate();
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void repacknsp()
        {
            statuslabel.Content = "Repacking NSP Container...";

            string nspbdir = AppDomain.CurrentDomain.BaseDirectory + "\\nspBuild.pyw";
            string[] tmpfiles = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + @"\\tmp");
            string args = String.Join(" ", tmpfiles);

            Process nsb = new Process();
            nsb.StartInfo.FileName = nspbdir;
            nsb.StartInfo.Arguments = args;
            nsb.StartInfo.CreateNoWindow = true;
            nsb.StartInfo.UseShellExecute = true;
            nsb.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            nsb.EnableRaisingEvents = true;

            nsb.Start();

            await Task.Run(() => nsb.WaitForExit());

            nsb.Close(); 

            stopbar();

            Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\\tmp", true);          

            System.Windows.MessageBox.Show("Congrats this NSP will now work on " + fwlabel.Content + "!");

            statuslabel.Content = "";
            keylabel.Content = "";
            fwlabel.Content = "";
            tidlabel.Content = "";

            onbtn();
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void carmdrm()
        {
            statuslbl.Content = "Converting File...";

            Extract("OSAC", AppDomain.CurrentDomain.BaseDirectory + "\\res", "res", "ffmpeg.exe");

            string ffdir = AppDomain.CurrentDomain.BaseDirectory + "\\res\\ffmpeg.exe";
            string arg = @"-y -activation_bytes ";
            string arg1 = @" -i ";
            string arg2 = @" -ab ";
            string arg3 = @"k -map_metadata 0 -id3v2_version 3 -vn ";
            string fileout = Path.Combine(outputdisplay.Text, Path.GetFileNameWithoutExtension(inputdisplay.Text) + GetOutExtension());
            string arguments = arg + abytes + arg1 + inputdisplay.Text + arg2 + qlabel.Content + arg3 + fileout;

            Process ffm = new Process();
            ffm.StartInfo.FileName = ffdir;
            ffm.StartInfo.Arguments = arguments;
            ffm.StartInfo.CreateNoWindow = true;
            ffm.StartInfo.RedirectStandardError = true;
            ffm.StartInfo.UseShellExecute = false;
            ffm.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            ffm.EnableRaisingEvents = true;
            Console.SetOut(new TextBoxWriter(txtConsole));
            ffm.ErrorDataReceived += (s, ea) =>
            {
                Console.WriteLine($"{ea.Data}");
            };

            scrolltimer.Tick += new EventHandler(scrolltimer_Tick);
            scrolltimer.Interval = new TimeSpan(0, 0, 1);

            ffm.Start();

            ffm.BeginErrorReadLine();
            scrolltimer.Start();

            await Task.Run(() => ffm.WaitForExit());

            ffm.Close();

            inpbutton.IsEnabled = true;

            convertbutton.IsEnabled = true;

            scrolltimer.Stop();
            scrolltimer.Tick -= new EventHandler(scrolltimer_Tick);

            enrb();
            enbslst();

            statuslbl.Content = "Conversion Complete!";

            stopbar();

            Directory.Delete(resdir, true);
        }

19 Source : TestFramework.cs
with MIT License
from adrianoc

public static void Execute(string executable, string args)
        {
            var processInfo = new ProcessStartInfo(executable, args);
            processInfo.CreateNoWindow = true;
            processInfo.RedirectStandardError = true;
            processInfo.RedirectStandardOutput = true;
            processInfo.UseShellExecute = false;

            var process = Process.Start(processInfo);

            var err = new StringBuilder();
            var @out = new StringBuilder();

            process.ErrorDataReceived += (sender, arg) => err.AppendLine(arg.Data);
            process.OutputDataReceived += (sender, arg) => @out.AppendLine(arg.Data);

            process.BeginErrorReadLine();
            process.BeginOutputReadLine();

            process.EnableRaisingEvents = true;
            process.WaitForExit();

            if (!string.IsNullOrWhiteSpace(@out.ToString()))
            {
                Console.WriteLine($"{Environment.NewLine}Output: {@out}");
            }
            
            if (!string.IsNullOrWhiteSpace(err.ToString()))
            {
                throw new ApplicationException("Error: " + err + $"{Environment.NewLine}Executable: {executable}");
            }
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void applyupdate()
        {
            statuslabel.Content = "Merging NCA's...";

            string curdir = AppDomain.CurrentDomain.BaseDirectory;
            string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";
            string upddir = AppDomain.CurrentDomain.BaseDirectory + "\\upd";
            string nspudir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
            string basenca = tmpdir + "\\NCAID_PLAIN.nca";

            var di = new DirectoryInfo(upddir);
            var result = di.GetFiles().OrderByDescending(x => x.Length).Take(1).ToList();
            var larupdnca = di.GetFiles().OrderByDescending(x => x.Length).Take(1).Select(x => x.FullName).ToList();

            string updnca = String.Join(" ", larupdnca);

            string replacedlkeyp = updreplacedlkyinput.Text;
            string upgtk = new string(replacedlkeyp.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray());

            string arg1 = @"-k keys.txt " + "--replacedlekey=" + upgtk + " --basenca=" + basenca + " --section1=" + curdir + "\\romfs.bin" + " --exefsdir=";
            string arg2 = tmpdir + "\\exefs " + updnca;
            string arg = arg1 + arg2; 

            Process aplupd = new Process();
            aplupd.StartInfo.FileName = nspudir;
            aplupd.StartInfo.Arguments = arg;
            aplupd.StartInfo.CreateNoWindow = true;
            aplupd.StartInfo.UseShellExecute = false;
            aplupd.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            aplupd.EnableRaisingEvents = true;

            aplupd.Start();

            await Task.Run(() => aplupd.WaitForExit());

            aplupd.Close();

            stopbar();

            statuslabel.Content = "";

            Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\\tmp", true);
            Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\\upd", true);

            onbtn();

            System.Windows.MessageBox.Show("Update applyment finished.\nYou can now use your updated romFS via fs-mitm.");
        }

19 Source : Program.cs
with GNU General Public License v3.0
from Aeroblast

static void DeDRM(string file)
        {
            string fn = "";
            if (File.Exists("dedrm.bat")) { fn = "dedrm.bat"; }
            else if (File.Exists("..\\dedrm.bat")) { fn = "..\\dedrm.bat"; }
            else { Log.log("Cannot found dedrm.bat"); return; }
            Process p = new Process();
            p.StartInfo.FileName = fn;
            p.StartInfo.Arguments = "\"" + file + "\"";
            p.Start();
            p.WaitForExit();
        }

19 Source : ExternalEditor.cs
with GNU General Public License v3.0
from ahmed605

public void LaunchEditor(FileSystem fs, File file)
        {
            if (fs is RealFileSystem)
            {
                // We'll edit RealFileSystems on the spot... no memory caching
                // Some of the files are pretty big...

                DirectoryInfo parent = new DirectoryInfo((fs as RealFileSystem).RealDirectory).Parent;
                string filename = parent == null ? file.FullName : Path.Combine(parent.FullName, file.FullName);

                var info = new ProcessStartInfo(filename);
                info.UseShellExecute = true;

                var p = Process.Start(info);
                if (p != null)
                {
                    p.WaitForExit();
                }
            }
            else
            {
                // Export the file to a temporary file and load it up

                string tempFileName = Path.Combine(Path.GetTempPath(), file.Name);
                System.IO.File.WriteAllBytes(tempFileName, file.GetData());

                var info = new ProcessStartInfo(tempFileName);
                info.UseShellExecute = true;

                var p = Process.Start(info);
                if (p != null)
                {
                    p.WaitForExit();

                    if (p.ExitCode == 0)
                    {
                        var data = System.IO.File.ReadAllBytes(tempFileName);
                        file.SetData(data);
                    }
                }

            }
        }

19 Source : EmulatorClientSocket.cs
with MIT License
from alanplotko

private void setupPortForwarding(int port) {
#if !UNITY_WEBPLAYER
      string adbCommand = string.Format("adb forward tcp:{0} tcp:{0}", port);
      System.Diagnostics.Process myProcess = new System.Diagnostics.Process();

#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
      string processFilename = "CMD.exe";
      string processArguments = @"/k " + adbCommand + " & exit";

      // See "Common Error Lookup Tool" (https://www.microsoft.com/en-us/download/details.aspx?id=985)
      // MSG_DIR_BAD_COMMAND_OR_FILE (cmdmsg.h)
      int kExitCodeCommandNotFound = 9009; // 0x2331

#else
      string processFilename = "bash";
      string processArguments = string.Format("-l -c \"{0}\"", adbCommand);

      // "command not found" (see http://tldp.org/LDP/abs/html/exitcodes.html)
      int kExitCodeCommandNotFound = 127;
#endif // UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN

      System.Diagnostics.ProcessStartInfo myProcessStartInfo =
        new System.Diagnostics.ProcessStartInfo(processFilename, processArguments);
      myProcessStartInfo.UseShellExecute = false;
      myProcessStartInfo.RedirectStandardError = true;
      myProcessStartInfo.CreateNoWindow = true;
      myProcess.StartInfo = myProcessStartInfo;
      myProcess.Start();
      myProcess.WaitForExit();
      // Also wait for HasExited here, to avoid ExitCode access below occasionally throwing InvalidOperationException
      while (!myProcess.HasExited) {
        Thread.Sleep(1);
      }
      int exitCode = myProcess.ExitCode;
      string standardError = myProcess.StandardError.ReadToEnd();
      myProcess.Close();

      if (exitCode == 0) {
        // Port forwarding setup successfully.
        return;
      }

      if (exitCode == kExitCodeCommandNotFound) {
        // Caught by phoneEventSocketLoop.
        throw new Exception(
          "Android Debug Bridge (`adb`) command not found." +
          "\nVerify that the Android SDK is installed and that the directory containing" +
          " `adb` is included in your PATH environment variable.");
      }
      // Caught by phoneEventSocketLoop.
      throw new Exception(
        String.Format(
          "Failed to setup port forwarding." +
          " Exit code {0} returned by process: {1} {2}\n{3}",
          exitCode, processFilename, processArguments, standardError));
#endif  // !UNITY_WEBPLAYER
    }

19 Source : MacUtils.cs
with GNU General Public License v3.0
from alexdillon

public static string RunAppleScriptCommand(string command)
        {
            var psInfo = new ProcessStartInfo("osascript");
            psInfo.ArgumentList.Add($"-e {command}");

            psInfo.RedirectStandardOutput = true;
            psInfo.RedirectStandardError = true;

            var p = Process.Start(psInfo);
            p.WaitForExit();
            var result = p.StandardOutput.ReadToEnd();

            return result;
        }

19 Source : EditSnapshotRuleForm.General.cs
with MIT License
from alexis-

private void btnSystemProtection_Click(object sender, EventArgs e)
    {
      Task.Run(() =>
      {
        var p = Process.Start("SystemPropertiesProtection.exe");

        p.WaitForExit();

        SendOrPostCallback callback = new SendOrPostCallback(args => { ListVSSVolumes(); });

        SyncContext.Send(callback, null);
      });
    }

19 Source : InstallUtils.cs
with MIT License
from alexis-

public static bool TaskExists(string taskName)
    {
      var p = CreateProcess(
        "schtasks",
        String.Format(QueryTask, taskName)
      );
      p.Start();
      p.WaitForExit();

      return p.ExitCode == 0;
    }

19 Source : InstallUtils.cs
with MIT License
from alexis-

public static bool CreateStartupTask(string taskName, string filePath)
    {
      var p = CreateProcess(
        "schtasks",
        String.Format(InstallScTask, taskName, filePath)
      );
      p.Start();
      p.WaitForExit();

      return p.ExitCode == 0;
    }

19 Source : InstallUtils.cs
with MIT License
from alexis-

public static bool DeleteStartupTask(string taskName)
    {
      var p = CreateProcess(
        "schtasks",
        String.Format(UninstallScTask, taskName)
      );
      p.Start();
      p.WaitForExit();

      return p.ExitCode == 0;
    }

19 Source : Splitting.cs
with MIT License
from Alkl58

private static void FFmpegSceneDetect()
        {
            // Skip Scene Detect if the file already exist
            if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "splits.txt")) == false)
            {
                Helpers.Logging("Scene Detection with FFmpeg");

                List<string> scenes = new List<string>();

                // Starts FFmpeg Process
                Process FFmpegSceneDetect = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    WindowStyle = ProcessWindowStyle.Hidden,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    WorkingDirectory = Global.FFmpeg_Path,
                    RedirectStandardError = true,
                    FileName = "cmd.exe",
                    Arguments = "/C ffmpeg.exe -i " + '\u0022' + Global.Video_Path + '\u0022' + " -hide_banner -loglevel 32 -filter_complex select=" + '\u0022' + "gt(scene\\," + FFmpeg_Threshold + "),select=eq(key\\,1),showinfo" + '\u0022' + " -an -f null -"
                };
                FFmpegSceneDetect.StartInfo = startInfo;
                FFmpegSceneDetect.Start();

                // Reads Standard Err from FFmpeg Output
                string stream = FFmpegSceneDetect.StandardError.ReadToEnd();

                FFmpegSceneDetect.WaitForExit();

                // Splits the Console Output by spaces
                string[] array = stream.Split(' ');

                // Searches for pts_time, if found it removes "pts_time:" to get only values
                foreach (string value in array) { if (value.Contains("pts_time:")) { scenes.Add(value.Remove(0, 9)); } }

                // Temporary value for Arg creation
                string previousScene = "0.000";

                // Clears the Args List to avoid conflicts in Batch Encode Mode
                FFmpegArgs.Clear();

                // Creates the seeking args for ffmpeg piping
                foreach (string sc in scenes)
                {
                    FFmpegArgs.Add("-ss " + previousScene + " -to " + sc);
                    previousScene = sc;
                }
                // Argument for seeking until the end of the video
                FFmpegArgs.Add("-ss " + previousScene);

                // Writes splitting arguments to text file
                foreach (string line in FFmpegArgs)
                {
                    using (StreamWriter sw = File.AppendText(Path.Combine(Global.temp_path, Global.temp_path_folder, "splits.txt")))
                    {
                        sw.WriteLine(line);
                        sw.Close();
                    }
                }

                if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "splits.txt")))
                {
                    Global.Video_Chunks = File.ReadAllLines(Path.Combine(Global.temp_path, Global.temp_path_folder, "splits.txt")); // Reads the split file for VideoEncode() function
                }
            }
        }

19 Source : EncodeVideoPipe.cs
with MIT License
from Alkl58

public static void Encode()
        {
            // Main Encoding Function
            // Creates a new Thread Pool
            using (SemapreplacedSlim concurrencySemapreplaced = new SemapreplacedSlim(EncodeVideo.Worker_Count))
            {
                // Creates a tasks list
                List<Task> tasks = new List<Task>();
                // Iterates over all args in VideoChunks list
                foreach (var command in Global.Video_Chunks)
                {
                    concurrencySemapreplaced.Wait();
                    var task = Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            if (!SmallFunctions.Cancel.CancelAll)
                            {
                                // We need the index of the command in the array
                                var index = Array.FindIndex(Global.Video_Chunks, row => row.Contains(command));
                                // Logic for resume mode - skips already encoded files
                                if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".ivf" + "_finished.log")) == false)
                                {
                                    // One Preplaced Encoding
                                    Process ffmpegProcess = new Process();
                                    ProcessStartInfo startInfo = new ProcessStartInfo
                                    {
                                        UseShellExecute = true,
                                        FileName = "cmd.exe",
                                        WorkingDirectory = Global.FFmpeg_Path
                                    };

                                    if (!EncodeVideo.Show_Terminal)
                                    {
                                        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                                    }

                                    string InputVideo = "";

                                    if (Splitting.split_type >= 1)
                                    {
                                        // FFmpeg Scene Detect or PySceneDetect
                                        InputVideo = " -i " + '\u0022' + Global.Video_Path + '\u0022' + " " + command;
                                    }
                                    else if (Splitting.split_type == 0)
                                    {
                                        // Chunk based splitting
                                        InputVideo = " -i " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", command) + '\u0022';
                                    }

                                    // Saves encoder progress to log file
                                    string ffmpeg_progress = " -progress " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Progress", "split" + index.ToString("D5") + "_progress.log") + '\u0022';

                                    // FFmpeg Pipe
                                    string ffmpeg_input = InputVideo + " " + MainWindow.FilterCommand + EncodeVideo.Pixel_Format + " -color_range 0 " + MainWindow.VSYNC + " -f yuv4mpegpipe - | ";

                                    // Process Exit Code
                                    int exit_code = 0;

                                    // Logic to skip first preplaced encoding if "_finished" log file exists
                                    if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log" + "_finished.log")) == false)
                                    {
                                        string encoderCMD = "";

                                        if (MainWindow.OnePreplaced)
                                        {
                                            // One Preplaced Encoding

                                            if (MainWindow.EncodeMethod == 5)
                                            {
                                                // aomenc
                                                encoderCMD = '\u0022' + Path.Combine(Global.Aomenc_Path, "aomenc.exe") + '\u0022' + " - --preplacedes=1 " + EncodeVideo.Final_Encoder_Command + " --output=";
                                            }
                                            else if (MainWindow.EncodeMethod == 6)
                                            {
                                                // rav1e
                                                encoderCMD = '\u0022' + Path.Combine(Global.Rav1e__Path, "rav1e.exe") + '\u0022' + " - " + EncodeVideo.Final_Encoder_Command + " --output ";
                                            }
                                            else if (MainWindow.EncodeMethod == 7)
                                            {
                                                // svt-av1
                                                ffmpeg_input = InputVideo + " " + MainWindow.FilterCommand + EncodeVideo.Pixel_Format + " -color_range 0 -nostdin " + MainWindow.VSYNC + " -f yuv4mpegpipe - | ";
                                                encoderCMD = '\u0022' + Path.Combine(Global.SvtAv1_Path, "SvtAv1EncApp.exe") + '\u0022' + " -i stdin " + EncodeVideo.Final_Encoder_Command + " --preplacedes 1 -b ";
                                            }

                                            encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".ivf") + '\u0022';
                                        }
                                        else
                                        {
                                            // Two Preplaced Encoding - First Preplaced

                                            if (MainWindow.EncodeMethod == 5)
                                            {
                                                // aomenc
                                                encoderCMD = '\u0022' + Path.Combine(Global.Aomenc_Path, "aomenc.exe") + '\u0022' + " - --preplacedes=2 --preplaced=1 " + EncodeVideo.Final_Encoder_Command + " --fpf=";
                                                encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log") + '\u0022' + " --output=NUL";
                                            }
                                            else if (MainWindow.EncodeMethod == 7)
                                            {
                                                // svt-av1
                                                ffmpeg_input = InputVideo + " " + MainWindow.FilterCommand + EncodeVideo.Pixel_Format + " -color_range 0 -nostdin " + MainWindow.VSYNC + " -f yuv4mpegpipe - | ";
                                                encoderCMD = '\u0022' + Path.Combine(Global.SvtAv1_Path, "SvtAv1EncApp.exe") + '\u0022' + " -i stdin " + EncodeVideo.Final_Encoder_Command + " --irefresh-type 2 --preplaced 1 -b NUL --stats ";
                                                encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log") + '\u0022';
                                            }
                                        }

                                        startInfo.Arguments = "/C ffmpeg.exe " + ffmpeg_progress + ffmpeg_input + encoderCMD;

                                        Helpers.Logging("Encoding Video: " + startInfo.Arguments);
                                        ffmpegProcess.StartInfo = startInfo;
                                        ffmpegProcess.Start();

                                        // Sets the process priority
                                        if (!EncodeVideo.Process_Priority)
                                            ffmpegProcess.PriorityClreplaced = ProcessPriorityClreplaced.BelowNormal;

                                        // Get launched Process ID
                                        int temp_pid = ffmpegProcess.Id;

                                        // Add Process ID to Array, inorder to keep track / kill the instances
                                        Global.Launched_PIDs.Add(temp_pid);

                                        ffmpegProcess.WaitForExit();

                                        // Get Exit Code
                                        exit_code = ffmpegProcess.ExitCode;

                                        if (exit_code != 0)
                                            Helpers.Logging("Chunk " + command + " Failed with Exit Code: " + exit_code.ToString());

                                        // Remove PID from Array after Exit
                                        Global.Launched_PIDs.RemoveAll(i => i == temp_pid);

                                        if (MainWindow.OnePreplaced == false && SmallFunctions.Cancel.CancelAll == false && exit_code == 0)
                                        {
                                            // Writes log file if first preplaced is finished, to be able to skip them later if in resume mode
                                            Helpers.WriteToFileThreadSafe("", Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log" + "_finished.log"));
                                        }
                                    }

                                    if (!MainWindow.OnePreplaced)
                                    {
                                        // Creates a different progress file for the second preplaced (avoids negative frame progressbar)
                                        ffmpeg_progress = " -progress " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Progress", "split" + index.ToString("D5") + "_progress_2nd.log") + '\u0022';

                                        string encoderCMD = "";

                                        if (MainWindow.EncodeMethod == 5)
                                        {
                                            // aomenc
                                            encoderCMD = '\u0022' + Path.Combine(Global.Aomenc_Path, "aomenc.exe") + '\u0022' + " - --preplacedes=2 --preplaced=2 " + EncodeVideo.Final_Encoder_Command + " --fpf=";
                                            encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log") + '\u0022' + " --output=";
                                        }
                                        else if (MainWindow.EncodeMethod == 7)
                                        {
                                            // svt-av1
                                            ffmpeg_input = InputVideo + " " + MainWindow.FilterCommand + EncodeVideo.Pixel_Format + " -color_range 0 -nostdin " + MainWindow.VSYNC + " -f yuv4mpegpipe - | ";
                                            encoderCMD = '\u0022' + Path.Combine(Global.SvtAv1_Path, "SvtAv1EncApp.exe") + '\u0022' + " -i stdin " + EncodeVideo.Final_Encoder_Command + " --irefresh-type 2 --preplaced 2 --stats ";
                                            encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log") + '\u0022' + " -b ";
                                        }

                                        encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".ivf") + '\u0022';

                                        startInfo.Arguments = "/C ffmpeg.exe " + ffmpeg_progress + ffmpeg_input + encoderCMD;
                                        Helpers.Logging("Encoding Video: " + startInfo.Arguments);
                                        ffmpegProcess.StartInfo = startInfo;
                                        ffmpegProcess.Start();

                                        // Sets the process priority
                                        if (!EncodeVideo.Process_Priority)
                                            ffmpegProcess.PriorityClreplaced = ProcessPriorityClreplaced.BelowNormal;

                                        // Get launched Process ID
                                        int temp_pid = ffmpegProcess.Id;

                                        // Add Process ID to Array, inorder to keep track / kill the instances
                                        Global.Launched_PIDs.Add(temp_pid);

                                        ffmpegProcess.WaitForExit();

                                        // Get Exit Code
                                        exit_code = ffmpegProcess.ExitCode;

                                        if (exit_code != 0)
                                            Helpers.Logging("Chunk " + command + " Failed with Exit Code: " + exit_code.ToString());

                                        // Remove PID from Array after Exit
                                        Global.Launched_PIDs.RemoveAll(i => i == temp_pid);
                                    }

                                    if (SmallFunctions.Cancel.CancelAll == false && exit_code == 0)
                                    {
                                        // This function will write finished encodes to a log file, to be able to skip them if in resume mode
                                        Helpers.WriteToFileThreadSafe("", Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".ivf" + "_finished.log"));
                                    }
                                }
                            }
                        }
                        finally { concurrencySemapreplaced.Release(); }
                    });
                    tasks.Add(task);
                }
                Task.WaitAll(tasks.ToArray());
            }
        }

19 Source : Splitting.cs
with MIT License
from Alkl58

private static void PySceneDetect()
        {
            // Skip Scene Detect if the file already exist
            if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "splits.txt")) == false)
            {
                Helpers.Logging("Scene Detection with PySceneDetect");
                // Detects the Scenes with PySceneDetect
                Process pySceneDetect = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    WindowStyle = ProcessWindowStyle.Hidden,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    FileName = "cmd.exe",
                    Arguments = "/C scenedetect -i " + '\u0022' + Global.Video_Path + '\u0022' + " -o " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder) + '\u0022' + " detect-content list-scenes"
                };
                pySceneDetect.StartInfo = startInfo;

                pySceneDetect.Start();

                pySceneDetect.WaitForExit();

                PySceneDetectParse();
            }
        }

19 Source : SmallFunctions.cs
with MIT License
from Alkl58

public static void ExecuteFfmpegTask(string ffmpegCommand)
        {
            //Run ffmpeg command
            Process process = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                WindowStyle = ProcessWindowStyle.Hidden,
                FileName = "cmd.exe",
                WorkingDirectory = Global.FFmpeg_Path,
                Arguments = ffmpegCommand
            };
            process.StartInfo = startInfo;
            process.Start();
            process.WaitForExit();
        }

19 Source : SmallFunctions.cs
with MIT License
from Alkl58

public static void ExecuteMKVMergeTask(string mkvmergeCommand)
        {
            //Run mkvmerge command
            Process process = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                WindowStyle = ProcessWindowStyle.Hidden,
                FileName = "cmd.exe",
                RedirectStandardOutput = true,
                CreateNoWindow = false,
                UseShellExecute = false,
                WorkingDirectory = Global.MKVToolNix_Path,
                Arguments = mkvmergeCommand
            };
            process.StartInfo = startInfo;
            process.Start();
            string _output = process.StandardOutput.ReadToEnd();
            process.WaitForExit();

            if (process.ExitCode != 0)
            {
                Helpers.Logging(_output);
                MessageBox.Show(_output, "mkvmerge", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }

19 Source : SmallFunctions.cs
with MIT License
from Alkl58

public static void GetSourceFrameCount(string source)
        {
            // Skip Framecount Calculation if it already "exists" (Resume Mode)
            if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "framecount.log")) == false)
            {
                // This function calculates the total number of frames
                Process process = new Process
                {
                    StartInfo = new ProcessStartInfo()
                    {
                        UseShellExecute = false,
                        CreateNoWindow = true,
                        WindowStyle = ProcessWindowStyle.Hidden,
                        FileName = "cmd.exe",
                        WorkingDirectory = Global.FFmpeg_Path,
                        Arguments = "/C ffmpeg.exe -i " + '\u0022' + source + '\u0022' + " -hide_banner -loglevel 32 -map 0:v:0 -f null -",
                        RedirectStandardError = true,
                        RedirectStandardOutput = true
                    }
                };
                process.Start();
                string stream = process.StandardError.ReadToEnd();
                process.WaitForExit();
                string tempStream = stream.Substring(stream.LastIndexOf("frame="));
                string data = GetBetween(tempStream, "frame=", "fps=");
                MainWindow.TotalFrames = int.Parse(data);
                Helpers.WriteToFileThreadSafe(data, Path.Combine(Global.temp_path, Global.temp_path_folder, "framecount.log"));
            }
            else
            {
                // Reads the first line of the framecount file
                MainWindow.TotalFrames = int.Parse(File.ReadLines(Path.Combine(Global.temp_path, Global.temp_path_folder, "framecount.log")).First());
            }
        }

19 Source : WordManipulationTests.cs
with MIT License
from alkampfergit

private void Open(string baseFile)
        {
            if (Environment.UserInteractive)
            {
                var process = System.Diagnostics.Process.Start(baseFile);
                process.WaitForExit();
            }
        }

19 Source : Concatenate.cs
with MIT License
from Alkl58

public static void Concat(string videoOutput, bool audioOutput, string currentPath, string ffmpegPath, bool trackone, bool tracktwo, bool trackthree, bool trackfour)
        {
            if (MainWindow.Cancel.CancelAll == false)
            {

                string outputfilename = videoOutput;

                //Lists all ivf files in mylist.txt
                Process process = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                startInfo.FileName = "cmd.exe";
                //FFmpeg Arguments
                startInfo.Arguments = "/C (for %i in ("+ '\u0022' + currentPath + "\\Chunks\\*.ivf"+ '\u0022' + ") do @echo file '%i') > "+ '\u0022' + currentPath+"\\Chunks\\mylist.txt"+ '\u0022';
                Console.WriteLine(startInfo.Arguments);
                process.StartInfo = startInfo;
                process.Start();
                process.WaitForExit();

                if (audioOutput == false)
                {
                    //Concat the Videos
                    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    startInfo.FileName = "cmd.exe";
                    startInfo.WorkingDirectory = ffmpegPath;
                    //FFmpeg Arguments
                    startInfo.Arguments = "/C ffmpeg.exe -f concat -safe 0 -i " + '\u0022' + currentPath + "\\Chunks\\mylist.txt"+ '\u0022' + " -c copy " + '\u0022' + outputfilename + '\u0022';
                    Console.WriteLine(startInfo.Arguments);
                    process.StartInfo = startInfo;
                    process.Start();
                    process.WaitForExit();
                }
                else if (audioOutput == true)
                {
                    //Concat the Videos
                    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    startInfo.FileName = "cmd.exe";
                    startInfo.WorkingDirectory = ffmpegPath;
                    //FFmpeg Arguments
                    startInfo.Arguments = "/C ffmpeg.exe -f concat -safe 0 -i " + '\u0022' + currentPath + "\\Chunks\\mylist.txt" + '\u0022' + " -c copy "+ '\u0022' + currentPath+"\\no_audio.mkv" + '\u0022';
                    Console.WriteLine(startInfo.Arguments);
                    process.StartInfo = startInfo;
                    process.Start();
                    process.WaitForExit();

                    //Concat the Videos
                    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    startInfo.FileName = "cmd.exe";
                    startInfo.WorkingDirectory = ffmpegPath;
                    //FFmpeg Arguments
                    //Sets the mapping of the video and audiostreams and muxes them
                    if (MainWindow.numberOfAudioTracks == 1)
                    {
                        startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + currentPath + "\\no_audio.mkv" + '\u0022' + " -i " + '\u0022' + currentPath + "\\AudioEncoded\\audio0.mkv" + '\u0022' + " -map 0:v -map 1:a -c copy " + '\u0022' + outputfilename + '\u0022';

                    }
                    else if (MainWindow.numberOfAudioTracks == 2)
                    {
                        startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + currentPath + "\\no_audio.mkv" + '\u0022' + " -i " + '\u0022' + currentPath + "\\AudioEncoded\\audio0.mkv" + '\u0022' + " -i " + '\u0022' + currentPath + "\\AudioEncoded\\audio1.mkv" + '\u0022' + " -map 0:v -map 1:a -map 2:a -c copy " + '\u0022' + outputfilename + '\u0022';

                    }
                    else if (MainWindow.numberOfAudioTracks == 3)
                    {

                        startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + currentPath + "\\no_audio.mkv" + '\u0022' + " -i " + '\u0022' + currentPath + "\\AudioEncoded\\audio0.mkv" + '\u0022' + " -i " + '\u0022' + currentPath + "\\AudioEncoded\\audio1.mkv" + '\u0022' + " -i " + '\u0022' + currentPath + "\\AudioEncoded\\audio2.mkv" + '\u0022' + " -map 0:v -map 1:a -map 2:a -map 3:a -c copy " + '\u0022' + outputfilename + '\u0022';

                    }
                    else if (MainWindow.numberOfAudioTracks == 4)
                    {
                        startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + currentPath + "\\no_audio.mkv" + '\u0022' + " -i " + '\u0022' + currentPath + "\\AudioEncoded\\audio0.mkv" + '\u0022' + " -i " + '\u0022' + currentPath + "\\AudioEncoded\\audio1.mkv" + '\u0022' + " -i " + '\u0022' + currentPath + "\\AudioEncoded\\audio2.mkv" + '\u0022' + " -i " + '\u0022' + currentPath + "\\AudioEncoded\\audio3.mkv" + '\u0022' + " -map 0:v -map 1:a -map 2:a -map 3:a -map 4:a -c copy " + '\u0022' + outputfilename + '\u0022';
                    }
                    //startInfo.Arguments = "/C ffmpeg.exe -i no_audio.mkv -i AudioEncoded\\audioOutput.mkv -map 0:0 -map 0:1 -map 0:2 -c copy " + '\u0022' + outputfilename + '\u0022';
                    Console.WriteLine(startInfo.Arguments);
                    process.StartInfo = startInfo;
                    process.Start();
                    process.WaitForExit();
                }

                if (MainWindow.shutdownafterencode == true && MainWindow.batchEncoding == false)
                {
                    if (MainWindow.Cancel.CancelAll == false)
                    {
                        //Shutdowns the PC if specified in settings
                        Process.Start("shutdown.exe", "/s /t 0");
                    }
                }
            }
        }

19 Source : EncodeVideo.cs
with MIT License
from Alkl58

public static void Encode()
        {
            // Main Encoding Function
            // Creates a new Thread Pool
            using (SemapreplacedSlim concurrencySemapreplaced = new SemapreplacedSlim(Worker_Count))
            {
                // Creates a tasks list
                List<Task> tasks = new List<Task>();
                // Iterates over all args in VideoChunks list
                foreach (var command in Global.Video_Chunks)
                {
                    concurrencySemapreplaced.Wait();
                    var task = Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            if (!SmallFunctions.Cancel.CancelAll)
                            {
                                // We need the index of the command in the array
                                var index = Array.FindIndex(Global.Video_Chunks, row => row.Contains(command));
                                // Logic for resume mode - skips already encoded files
                                if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".ivf" + "_finished.log")) == false)
                                {
                                    // One Preplaced Encoding
                                    Process ffmpegProcess = new Process();
                                    ProcessStartInfo startInfo = new ProcessStartInfo
                                    {
                                        UseShellExecute = true,
                                        FileName = "cmd.exe",
                                        WorkingDirectory = Global.FFmpeg_Path
                                    };

                                    if (!Show_Terminal)
                                    {
                                        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                                    }

                                    string InputVideo = "";

                                    if (Splitting.split_type >= 1)
                                    {
                                        // FFmpeg Scene Detect or PySceneDetect
                                        InputVideo = " -i " + '\u0022' + Global.Video_Path + '\u0022' + " " + command;
                                    }
                                    else if (Splitting.split_type == 0)
                                    {
                                        // Chunk based splitting
                                        InputVideo = " -i " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", command) + '\u0022';
                                    }

                                    // Saves encoder progress to log file
                                    string ffmpeg_progress = " -an -progress " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Progress", "split" + index.ToString("D5") + "_progress.log") + '\u0022';

                                    string ffmpeg_input = InputVideo + " " + MainWindow.FilterCommand + Pixel_Format + " " + MainWindow.VSYNC + " ";

                                    // Process Exit Code
                                    int exit_code = 0;

                                    // Logic to skip first preplaced encoding if "_finished" log file exists
                                    if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log" + "_finished.log")) == false)
                                    {
                                        string encoderCMD = "";

                                        if (MainWindow.OnePreplaced)
                                        {
                                            // One Preplaced Encoding
                                            encoderCMD = " -y " + Final_Encoder_Command + " ";
                                            encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".webm") + '\u0022';
                                        }
                                        else
                                        {
                                            // Two Preplaced Encoding - First Preplaced
                                            encoderCMD = " -y " + Final_Encoder_Command + " -preplaced 1 -preplacedlogfile ";
                                            encoderCMD += '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log") + '\u0022' + " -f webm NUL";
                                        }

                                        startInfo.Arguments = "/C ffmpeg.exe " + ffmpeg_progress + ffmpeg_input + encoderCMD;

                                        Helpers.Logging("Encoding Video: " + startInfo.Arguments);
                                        ffmpegProcess.StartInfo = startInfo;
                                        ffmpegProcess.Start();

                                        // Sets the process priority
                                        if (!Process_Priority)
                                            ffmpegProcess.PriorityClreplaced = ProcessPriorityClreplaced.BelowNormal;

                                        // Get launched Process ID
                                        int temp_pid = ffmpegProcess.Id;

                                        // Add Process ID to Array, inorder to keep track / kill the instances
                                        Global.Launched_PIDs.Add(temp_pid);

                                        ffmpegProcess.WaitForExit();

                                        // Get Exit Code
                                        exit_code = ffmpegProcess.ExitCode;

                                        if (exit_code != 0)
                                            Helpers.Logging("Chunk " + command + " Failed with Exit Code: " + exit_code.ToString());

                                        // Remove PID from Array after Exit
                                        Global.Launched_PIDs.RemoveAll(i => i == temp_pid);

                                        if (MainWindow.OnePreplaced == false && SmallFunctions.Cancel.CancelAll == false && exit_code == 0)
                                        {
                                            // Writes log file if first preplaced is finished, to be able to skip them later if in resume mode
                                            Helpers.WriteToFileThreadSafe("", Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log" + "_finished.log"));
                                        }
                                    }

                                    if (!MainWindow.OnePreplaced)
                                    {
                                        // Creates a different progress file for the second preplaced (avoids negative frame progressbar)
                                        ffmpeg_progress = " -an -progress " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Progress", "split" + index.ToString("D5") + "_progress_2nd.log") + '\u0022';

                                        string encoderCMD = " -preplaced 2 " + Final_Encoder_Command;

                                        encoderCMD += " -preplacedlogfile " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + "_stats.log") + '\u0022';
                                        encoderCMD += " " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".webm") + '\u0022';

                                        startInfo.Arguments = "/C ffmpeg.exe " + ffmpeg_progress + ffmpeg_input + encoderCMD;
                                        Helpers.Logging("Encoding Video: " + startInfo.Arguments);
                                        ffmpegProcess.StartInfo = startInfo;
                                        ffmpegProcess.Start();

                                        // Sets the process priority
                                        if (!Process_Priority)
                                            ffmpegProcess.PriorityClreplaced = ProcessPriorityClreplaced.BelowNormal;

                                        // Get launched Process ID
                                        int temp_pid = ffmpegProcess.Id;

                                        // Add Process ID to Array, inorder to keep track / kill the instances
                                        Global.Launched_PIDs.Add(temp_pid);

                                        ffmpegProcess.WaitForExit();

                                        // Get Exit Code
                                        exit_code = ffmpegProcess.ExitCode;

                                        if (exit_code != 0)
                                            Helpers.Logging("Chunk " + command + " Failed with Exit Code: " + exit_code.ToString());

                                        // Remove PID from Array after Exit
                                        Global.Launched_PIDs.RemoveAll(i => i == temp_pid);
                                    }

                                    if (SmallFunctions.Cancel.CancelAll == false && exit_code == 0)
                                    {
                                        // This function will write finished encodes to a log file, to be able to skip them if in resume mode
                                        Helpers.WriteToFileThreadSafe("", Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split" + index.ToString("D5") + ".ivf" + "_finished.log"));
                                    }
                                }
                            }
                        }
                        finally { concurrencySemapreplaced.Release(); }
                    });
                    tasks.Add(task);
                }
                Task.WaitAll(tasks.ToArray());
            }
        }

19 Source : Split.cs
with MIT License
from Alkl58

public static void Splitting(string videoInput, bool resume, bool logging, bool reencode, string chunkLength, string outputPath, string ffmpegPath)
        {
            //Start Splitting
            if (resume == false)
            {
                if (logging == true)
                {
                    SmallScripts.WriteToFileThreadSafe(DateTime.Now.ToString("h:mm:ss tt") + " Start Splitting", "log.log");
                }
                //pLabel.Dispatcher.Invoke(() => pLabel.Content = "Started Splitting...", DispatcherPriority.Background);
                Process process = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                startInfo.FileName = "cmd.exe";
                startInfo.WorkingDirectory = ffmpegPath;
                //FFmpeg Arguments

                //Checks if Source needs to be reencoded
                if (reencode == false)
                {
                    if (logging == true)
                    {
                        SmallScripts.WriteToFileThreadSafe(DateTime.Now.ToString("h:mm:ss tt") + " Splitting without reencoding", "log.log");
                    }
                    startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vcodec copy -f segment -segment_time " + chunkLength + " -an " + '\u0022' + outputPath + "\\Chunks\\out%0d.mkv" + '\u0022';
                }
                else if (reencode == true)
                {
                    if (logging == true)
                    {
                        SmallScripts.WriteToFileThreadSafe(DateTime.Now.ToString("h:mm:ss tt") + " Splitting with reencoding", "log.log");
                    }
                    startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -c:v utvideo -f segment -segment_time " + chunkLength + " -an " + '\u0022' + outputPath + "\\Chunks\\out%0d.mkv" + '\u0022';
                    Console.WriteLine(startInfo.Arguments);
                }
                //Console.WriteLine(startInfo.Arguments);
                process.StartInfo = startInfo;
                process.Start();
                process.WaitForExit();
                if (MainWindow.Cancel.CancelAll == false)
                {
                    SmallScripts.WriteToFileThreadSafe("True", outputPath + "\\splitted.log");
                }
            }
        }

19 Source : Splitting.cs
with MIT License
from Alkl58

private static void FFmpegChunking()
        {
            // Skips Splitting of already existent
            if (!File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "splitting.log")))
            {
                // Create Chunks Folder
                Helpers.Create_Temp_Folder(Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks"));

                // Generate Command
                string ffmpeg_command = "/C ffmpeg.exe";
                ffmpeg_command += " -y -i " + '\u0022' + Global.Video_Path + '\u0022';                                              // Video Input
                ffmpeg_command += " -reset_timestamps 1 -map_metadata -1 -sn -an";                                                  // Remove unnecessary metadata etc

                if (skip_reencode)
                {
                    ffmpeg_command += " -c:v copy";
                }
                else
                {
                    if (encode_method == 0)
                    {
                        ffmpeg_command += " -c:v libx264 -preset ultrafast -crf 0";                                                     // Re-Encoding - Needed because else it WILL loose frames
                    }
                    else if (encode_method == 1)
                    {
                        ffmpeg_command += " -c:v ffv1 -level 3 -threads 4 -coder 1 -context 1 -slicecrc 0 -slices 4";                   // Re-Encoding - Needed because else it WILL loose frames
                    }
                    else if (encode_method == 2)
                    {
                        ffmpeg_command += " -c:v utvideo";                                                                              // Re-Encoding - Needed because else it WILL loose frames
                    }

                    // Hardsub
                    if (MainWindow.subHardSubEnabled)
                    {
                        ffmpeg_command += " " + MainWindow.HardSubCommand;
                    }

                    // Filters
                    ffmpeg_command += MainWindow.FilterCommand;

                    // Reset Filter Command so it is not being used later by encoders
                    MainWindow.FilterCommand = "";

                    ffmpeg_command += " -sc_threshold 0 -g " + chunking_length;                                                         // Make Splitting more accurate
                    ffmpeg_command += " -force_key_frames " + '\u0022' + "expr:gte(t, n_forced * " + chunking_length + ")" + '\u0022';  // Make Splitting more accurate
                }

                ffmpeg_command += " -segment_time " + chunking_length + " -f segment " + '\u0022';                                  // Segmenting
                ffmpeg_command += Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "split%6d.mkv") + '\u0022';     // Video Output

                Helpers.Logging("Equal Chunking: " + ffmpeg_command);

                // Start Splitting
                Process chunking_process = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    WindowStyle = ProcessWindowStyle.Hidden,
                    FileName = "cmd.exe",
                    WorkingDirectory = Global.FFmpeg_Path,
                    Arguments = ffmpeg_command
                };
                chunking_process.StartInfo = startInfo;

                // Start Process
                chunking_process.Start();

                // Get launched Process ID
                int temp_pid = chunking_process.Id;

                // Add Process ID to Array, inorder to keep track / kill the instances
                Global.Launched_PIDs.Add(temp_pid);

                // Wait for Exit
                chunking_process.WaitForExit();

                // Get Exit Code
                int exit_code = chunking_process.ExitCode;

                // Remove PID from Array after Exit
                Global.Launched_PIDs.RemoveAll(i => i == temp_pid);

                // Write Save Point
                Helpers.WriteToFileThreadSafe("", Path.Combine(Global.temp_path, Global.temp_path_folder, "splitting.log"));
            }

            // Add Chunks to Array
            Global.Video_Chunks = Directory.GetFiles(Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks"), "*mkv", SearchOption.AllDirectories).Select(x => Path.GetFileName(x)).ToArray();
        }

See More Examples