Executing Batch File in C#

前端 未结 12 1773
有刺的猬
有刺的猬 2020-11-22 05:22

I\'m trying to execute a batch file in C#, but I\'m not getting any luck doing it.

I\'ve found multiple examples on the Internet doing it, but it is not working for

12条回答
  •  情歌与酒
    2020-11-22 05:55

    Here is sample c# code that are sending 2 parameters to a bat/cmd file for answer this question.

    Comment: how can I pass parameters and read a result of command execution?

    /by @Janatbek Sharsheyev

    Option 1 : Without hiding the console window, passing arguments and without getting the outputs

    • This is an edit from this answer /by @Brian Rasmussen
    using System;
    using System.Diagnostics;
    
    
    namespace ConsoleApplication
    {
        class Program
        { 
            static void Main(string[] args)
            {
             System.Diagnostics.Process.Start(@"c:\batchfilename.bat", "\"1st\" \"2nd\"");
            }
        }
    }
    

    Option 2 : Hiding the console window, passing arguments and taking outputs


    using System;
    using System.Diagnostics;
    
    namespace ConsoleApplication
    {
        class Program
        { 
            static void Main(string[] args)
            {
             var process = new Process();
             var startinfo = new ProcessStartInfo(@"c:\batchfilename.bat", "\"1st_arg\" \"2nd_arg\" \"3rd_arg\"");
             startinfo.RedirectStandardOutput = true;
             startinfo.UseShellExecute = false;
             process.StartInfo = startinfo;
             process.OutputDataReceived += (sender, argsx) => Console.WriteLine(argsx.Data); // do whatever processing you need to do in this handler
             process.Start();
             process.BeginOutputReadLine();
             process.WaitForExit();
            }
        }
    }
    

提交回复
热议问题