Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# arg.Append(“\”+args[i]+“\”); } 返回arg.ToString(); } 静态void Main(字符串[]参数) { 过程prc=新过程(); prc.StartInfo=//new ProcessStartInfo(“cmd.exe”,String.Format(“/c\”{0}\“{1}”,Path.Combine(Environment.CurrentDirectory,“mapTargetIDToTargetNameA3.bat”),buildargument(args)); //新的ProcessStartInfo(Path.Combine(Environment.CurrentDirectory,“mapTargetIDToTargetNameA3.bat”)、buildargument(args)); 新的ProcessStartInfo(“mapTargetIDToTargetNameA3.bat”); prc.StartInfo.Arguments=buildargument(args); prc.EnableRaisingEvents=真; if(redirectStandardOutput==true) { prc.StartInfo.UseShellExecute=false; } 其他的 { prc.StartInfo.UseShellExecute=true; } prc.StartInfo.CreateNoWindow=true; prc.OutputDataReceived+=OnOutputDataReceived; prc.ErrorDataReceived+=OnErrorDataReceived; //中国退出+=一个退出; prc.StartInfo.RedirectStandardOutput=RedirectStandardOutput; prc.StartInfo.RedirectStandardError=redirectStandardOutput; 尝试 { prc.Start(); prc.BeginOutputReadLine(); prc.BeginErrorReadLine(); 中华人民共和国;外国退出(); } 捕获(例外e) { Console.WriteLine(“操作系统错误:+e.Message”); } 中华人民共和国关闭(); } //处理dataevent OutputDataReceived上的私有静态无效(对象发送方、DataReceivedEventArgs e) { //对你的数据做点什么 控制台写入线(如数据); } //处理错误 私有静态无效OnErrorDataReceived(对象发送方,DataReceivedEventArgs e) { 控制台写入线(如数据); } //处理退出的事件并显示进程信息。 //私有静态void OnExited(对象发送方,System.EventArgs e) //{ //var进程=发送方作为进程; //if(进程!=null) // { //Console.WriteLine(“ExitCode:+process.ExitCode”); // } //否则 // { //Console.WriteLine(“进程已退出”); // } //} }_C#_Command Line - Fatal编程技术网

C# arg.Append(“\”+args[i]+“\”); } 返回arg.ToString(); } 静态void Main(字符串[]参数) { 过程prc=新过程(); prc.StartInfo=//new ProcessStartInfo(“cmd.exe”,String.Format(“/c\”{0}\“{1}”,Path.Combine(Environment.CurrentDirectory,“mapTargetIDToTargetNameA3.bat”),buildargument(args)); //新的ProcessStartInfo(Path.Combine(Environment.CurrentDirectory,“mapTargetIDToTargetNameA3.bat”)、buildargument(args)); 新的ProcessStartInfo(“mapTargetIDToTargetNameA3.bat”); prc.StartInfo.Arguments=buildargument(args); prc.EnableRaisingEvents=真; if(redirectStandardOutput==true) { prc.StartInfo.UseShellExecute=false; } 其他的 { prc.StartInfo.UseShellExecute=true; } prc.StartInfo.CreateNoWindow=true; prc.OutputDataReceived+=OnOutputDataReceived; prc.ErrorDataReceived+=OnErrorDataReceived; //中国退出+=一个退出; prc.StartInfo.RedirectStandardOutput=RedirectStandardOutput; prc.StartInfo.RedirectStandardError=redirectStandardOutput; 尝试 { prc.Start(); prc.BeginOutputReadLine(); prc.BeginErrorReadLine(); 中华人民共和国;外国退出(); } 捕获(例外e) { Console.WriteLine(“操作系统错误:+e.Message”); } 中华人民共和国关闭(); } //处理dataevent OutputDataReceived上的私有静态无效(对象发送方、DataReceivedEventArgs e) { //对你的数据做点什么 控制台写入线(如数据); } //处理错误 私有静态无效OnErrorDataReceived(对象发送方,DataReceivedEventArgs e) { 控制台写入线(如数据); } //处理退出的事件并显示进程信息。 //私有静态void OnExited(对象发送方,System.EventArgs e) //{ //var进程=发送方作为进程; //if(进程!=null) // { //Console.WriteLine(“ExitCode:+process.ExitCode”); // } //否则 // { //Console.WriteLine(“进程已退出”); // } //} }

C# arg.Append(“\”+args[i]+“\”); } 返回arg.ToString(); } 静态void Main(字符串[]参数) { 过程prc=新过程(); prc.StartInfo=//new ProcessStartInfo(“cmd.exe”,String.Format(“/c\”{0}\“{1}”,Path.Combine(Environment.CurrentDirectory,“mapTargetIDToTargetNameA3.bat”),buildargument(args)); //新的ProcessStartInfo(Path.Combine(Environment.CurrentDirectory,“mapTargetIDToTargetNameA3.bat”)、buildargument(args)); 新的ProcessStartInfo(“mapTargetIDToTargetNameA3.bat”); prc.StartInfo.Arguments=buildargument(args); prc.EnableRaisingEvents=真; if(redirectStandardOutput==true) { prc.StartInfo.UseShellExecute=false; } 其他的 { prc.StartInfo.UseShellExecute=true; } prc.StartInfo.CreateNoWindow=true; prc.OutputDataReceived+=OnOutputDataReceived; prc.ErrorDataReceived+=OnErrorDataReceived; //中国退出+=一个退出; prc.StartInfo.RedirectStandardOutput=RedirectStandardOutput; prc.StartInfo.RedirectStandardError=redirectStandardOutput; 尝试 { prc.Start(); prc.BeginOutputReadLine(); prc.BeginErrorReadLine(); 中华人民共和国;外国退出(); } 捕获(例外e) { Console.WriteLine(“操作系统错误:+e.Message”); } 中华人民共和国关闭(); } //处理dataevent OutputDataReceived上的私有静态无效(对象发送方、DataReceivedEventArgs e) { //对你的数据做点什么 控制台写入线(如数据); } //处理错误 私有静态无效OnErrorDataReceived(对象发送方,DataReceivedEventArgs e) { 控制台写入线(如数据); } //处理退出的事件并显示进程信息。 //私有静态void OnExited(对象发送方,System.EventArgs e) //{ //var进程=发送方作为进程; //if(进程!=null) // { //Console.WriteLine(“ExitCode:+process.ExitCode”); // } //否则 // { //Console.WriteLine(“进程已退出”); // } //} },c#,command-line,C#,Command Line,代码需要在VS2007内部编译,使用命令行csc.exe生成的可执行文件将无法正确显示控制台输出,甚至会因CLR20r3错误而崩溃。注释掉OnExited事件进程,bat to exe的控制台输出将更像原始的bat控制台输出。以下是一个小示例: using System; using System.Diagnostics; class Program { static void Main(string[] args) { var p = Process.Star

代码需要在VS2007内部编译,使用命令行csc.exe生成的可执行文件将无法正确显示控制台输出,甚至会因CLR20r3错误而崩溃。注释掉OnExited事件进程,bat to exe的控制台输出将更像原始的bat控制台输出。

以下是一个小示例:

using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        var p = Process.Start(
            new ProcessStartInfo("git", "branch --show-current")
            {
                CreateNoWindow = true,
                UseShellExecute = false,
                RedirectStandardError = true,
                RedirectStandardOutput = true,
                WorkingDirectory = Environment.CurrentDirectory
            }
        );

        p.WaitForExit();
        string branchName =p.StandardOutput.ReadToEnd().TrimEnd();
        string errorInfoIfAny =p.StandardError.ReadToEnd().TrimEnd();

        if (errorInfoIfAny.Length != 0)
        {
            Console.WriteLine($"error: {errorInfoIfAny}");
        }
        else { 
            Console.WriteLine($"branch: {branchName}");
        }

    }
}
我相信这是最简单的形式

请注意,大多数命令行工具很容易混淆标准输出和标准错误,有时将它们组合成单个字符串是有意义的


另外,
p.ExitCode
有时也可能有用。

有没有办法不用批处理文件就可以做到这一点?问题是,我需要向命令发送一些参数。我使用的是xsd.exe/type:,所以我需要能够设置程序集和类名,然后运行命令。您可以通过
{YourProcessObject}.StartInfo.Arguments
string。如何使进程以管理员身份运行?我遇到了一些问题,使用此代码的进程完全停止,因为进程已将足够的数据写入
p.StandardError
流。当流变满时,进程似乎将停止,直到数据被写入s已消耗,因此我必须同时读取
StandardError
StandardOutput
,以确保任务正确执行。c#compiler的Quick headsup:Process对象必须将UseShellExecute属性设置为false才能重定向IO流。这迫使您在需要权限的地方编写文件例如,需要找到的位置和名称,并且在完成后不要忘记删除。实际上更易于使用
RedirectStandardOutput
。一个非常全面的示例,ThanksMight希望将OutputDataReceived处理程序更改为stdOut.AppendLine()在我看来,这是一个比公认的答案更全面的解决方案。我现在正在使用它,还没有使用公认的解决方案,但这一解决方案看起来确实不足。感谢
process.StartInfo.RedirectStandardError=true;
if(process.ExitCode==0)
哪个被接受的答案没有。谢谢,它在Ubuntu 20 LTS上工作。(仅供记录)帮我省去了很多麻烦。谢谢。调用“sc”时,我还必须设置StartInfo.WindowStyle=ProcessWindowStyle.Hidden。另请参见-它显示输出和错误的事件。相关(但不捕获STDOUT):+1用于显示如何为运行命令行程序(接受的答案没有)添加参数。我认为这更好地回答了原始问题,因为它显示了如何通过C#(不是文件)运行CMD命令。当进程写入大量数据时,可能会死锁。最好在进程仍在运行时开始读取数据。您假设您具有写入权限,但这可能不是真的
 System.Diagnostics.ProcessStartInfo psi =
   new System.Diagnostics.ProcessStartInfo(@"program_to_call.exe");
 psi.RedirectStandardOutput = true;
 psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
 psi.UseShellExecute = false;
 System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi); ////
 System.IO.StreamReader myOutput = proc.StandardOutput;
 proc.WaitForExit(2000);
 if (proc.HasExited)
  {
      string output = myOutput.ReadToEnd();
 }
//Create process
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();

//strCommand is path and file name of command to run
pProcess.StartInfo.FileName = strCommand;

//strCommandParameters are parameters to pass to program
pProcess.StartInfo.Arguments = strCommandParameters;

pProcess.StartInfo.UseShellExecute = false;

//Set output of program to be written to process output stream
pProcess.StartInfo.RedirectStandardOutput = true;   

//Optional
pProcess.StartInfo.WorkingDirectory = strWorkingDirectory;

//Start the process
pProcess.Start();

//Get program output
string strOutput = pProcess.StandardOutput.ReadToEnd();

//Wait for process to finish
pProcess.WaitForExit();
pProcess.StartInfo.CreateNoWindow = true;
// usage
const string ToolFileName = "example.exe";
string output = RunExternalExe(ToolFileName);

public string RunExternalExe(string filename, string arguments = null)
{
    var process = new Process();

    process.StartInfo.FileName = filename;
    if (!string.IsNullOrEmpty(arguments))
    {
        process.StartInfo.Arguments = arguments;
    }

    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    process.StartInfo.UseShellExecute = false;

    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.RedirectStandardOutput = true;
    var stdOutput = new StringBuilder();
    process.OutputDataReceived += (sender, args) => stdOutput.AppendLine(args.Data); // Use AppendLine rather than Append since args.Data is one line of output, not including the newline character.

    string stdError = null;
    try
    {
        process.Start();
        process.BeginOutputReadLine();
        stdError = process.StandardError.ReadToEnd();
        process.WaitForExit();
    }
    catch (Exception e)
    {
        throw new Exception("OS error while executing " + Format(filename, arguments)+ ": " + e.Message, e);
    }

    if (process.ExitCode == 0)
    {
        return stdOutput.ToString();
    }
    else
    {
        var message = new StringBuilder();

        if (!string.IsNullOrEmpty(stdError))
        {
            message.AppendLine(stdError);
        }

        if (stdOutput.Length != 0)
        {
            message.AppendLine("Std output:");
            message.AppendLine(stdOutput.ToString());
        }

        throw new Exception(Format(filename, arguments) + " finished with exit code = " + process.ExitCode + ": " + message);
    }
}

private string Format(string filename, string arguments)
{
    return "'" + filename + 
        ((string.IsNullOrEmpty(arguments)) ? string.Empty : " " + arguments) +
        "'";
}
List<string[]> results = new List<string[]>();

        using (Process p = new Process())
        {
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.Arguments = "/c arp -a";
            p.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
            p.Start();

            string line;

            while ((line = p.StandardOutput.ReadLine()) != null)
            {
                if (line != "" && !line.Contains("Interface") && !line.Contains("Physical Address"))
                {
                    var lineArr = line.Trim().Split(' ').Select(n => n).Where(n => !string.IsNullOrEmpty(n)).ToArray();
                    var arrResult = new string[]
                {
                   lineArr[0],
                   lineArr[1],
                   lineArr[2]
                };
                    results.Add(arrResult);
                }
            }

            p.WaitForExit();
        }
using CliWrap;
using CliWrap.Buffered;

var result = await Cli.Wrap("target.exe")
   .WithArguments("arguments")
   .ExecuteBufferedAsync();

var stdout = result.StandardOutput;
        var p = new Process();
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.Arguments = "/c mycmd.exe 2>&1";
        var p = new Process();
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.Arguments = @"/c dir \windows";
        p.StartInfo.CreateNoWindow = true;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardInput = false;
        p.OutputDataReceived += (a, b) => Console.WriteLine(b.Data);
        p.ErrorDataReceived += (a, b) => Console.WriteLine(b.Data);
        p.Start();
        p.BeginErrorReadLine();
        p.BeginOutputReadLine();
        p.WaitForExit();
    private void butPython(object sender, EventArgs e)
    {
        llHello.Text = "Calling Python...";
        this.Refresh();
        Tuple<String,String> python = GoPython(@"C:\Users\BLAH\Desktop\Code\Python\BLAH.py");
        llHello.Text = python.Item1; // Show result.
        if (python.Item2.Length > 0) MessageBox.Show("Sorry, there was an error:" + Environment.NewLine + python.Item2);
    }

    public Tuple<String,String> GoPython(string pythonFile, string moreArgs = "")
    {
        ProcessStartInfo PSI = new ProcessStartInfo();
        PSI.FileName = "py.exe";
        PSI.Arguments = string.Format("\"{0}\" {1}", pythonFile, moreArgs);
        PSI.CreateNoWindow = true;
        PSI.UseShellExecute = false;
        PSI.RedirectStandardError = true;
        PSI.RedirectStandardOutput = true;
        using (Process process = Process.Start(PSI))
            using (StreamReader reader = process.StandardOutput)
            {
                string stderr = process.StandardError.ReadToEnd(); // Error(s)!!
                string result = reader.ReadToEnd(); // What we want.
                return new Tuple<String,String> (result,stderr); 
            }
    }
new Process() { StartInfo = new ProcessStartInfo("echo", "Hello, World") }.Start();
    var cliProcess = new Process() {
        StartInfo = new ProcessStartInfo("echo", "Hello, World") {
            UseShellExecute = false,
            RedirectStandardOutput = true
        }
    };
    cliProcess.Start();
    string cliOut = cliProcess.StandardOutput.ReadToEnd();
    cliProcess.WaitForExit();
    cliProcess.Close();
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C vol";
p.Start();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine(output);
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe";
p.Start();
// Read the output stream first and then wait.
p.StandardInput.WriteLine("vol");
p.StandardInput.WriteLine("exit");
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine(output);
// Start a process with the filename or path with filename e.g. "cmd". Please note the 
//using statemant
using myProcess.StartInfo.FileName = "cmd";
// add the arguments - Note add "/c" if you want to carry out tge  argument in cmd and  
// terminate
myProcess.StartInfo.Arguments = "/c dir";
// Allows to raise events
myProcess.EnableRaisingEvents = true;
//hosted by the application itself to not open a black cmd window
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.CreateNoWindow = true;
// Eventhander for data
myProcess.Exited += OnOutputDataRecived;
// Eventhandler for error
myProcess.ErrorDataReceived += OnErrorDataReceived;
// Eventhandler wich fires when exited
myProcess.Exited += OnExited;
// Starts the process
myProcess.Start();
//read the output before you wait for exit
myProcess.BeginOutputReadLine();
// wait for the finish - this will block (leave this out if you dont want to wait for 
// it, so it runs without blocking)
process.WaitForExit();

// Handle the dataevent
private void OnOutputDataRecived(object sender, DataReceivedEventArgs e)
{
    //do something with your data
    Trace.WriteLine(e.Data);
}

//Handle the error
private void OnErrorDataReceived(object sender, DataReceivedEventArgs e)
{        
    Trace.WriteLine(e.Data);
    //do something with your exception
    throw new Exception();
}    

// Handle Exited event and display process information.
private void OnExited(object sender, System.EventArgs e)
{
     Trace.WriteLine("Process exited");
}
using System;
using System.Text;  //StringBuilder
using System.Diagnostics;
using System.IO;


class Program
{
    private static bool redirectStandardOutput = true;

    private static string buildargument(string[] args)
    {
        StringBuilder arg = new StringBuilder();
        for (int i = 0; i < args.Length; i++)
        {
            arg.Append("\"" + args[i] + "\" ");
        }

        return arg.ToString();
    }

    static void Main(string[] args)
    {
        Process prc = new Process();
        prc.StartInfo = //new ProcessStartInfo("cmd.exe", String.Format("/c \"\"{0}\" {1}", Path.Combine(Environment.CurrentDirectory, "mapTargetIDToTargetNameA3.bat"), buildargument(args)));
        //new ProcessStartInfo(Path.Combine(Environment.CurrentDirectory, "mapTargetIDToTargetNameA3.bat"), buildargument(args));
        new ProcessStartInfo("mapTargetIDToTargetNameA3.bat");
        prc.StartInfo.Arguments = buildargument(args);

        prc.EnableRaisingEvents = true;

        if (redirectStandardOutput == true)
        {
            prc.StartInfo.UseShellExecute = false;
        }
        else
        {
            prc.StartInfo.UseShellExecute = true;
        }

        prc.StartInfo.CreateNoWindow = true;

        prc.OutputDataReceived += OnOutputDataRecived;
        prc.ErrorDataReceived += OnErrorDataReceived;
        //prc.Exited += OnExited;

        prc.StartInfo.RedirectStandardOutput = redirectStandardOutput;
        prc.StartInfo.RedirectStandardError = redirectStandardOutput;

        try
        {
            prc.Start();
            prc.BeginOutputReadLine();
            prc.BeginErrorReadLine();
            prc.WaitForExit();
        }
        catch (Exception e)
        {
            Console.WriteLine("OS error: " + e.Message);
        }

        prc.Close();
    }

    // Handle the dataevent
    private static void OnOutputDataRecived(object sender, DataReceivedEventArgs e)
    {
        //do something with your data
        Console.WriteLine(e.Data);
    }

    //Handle the error
    private static void OnErrorDataReceived(object sender, DataReceivedEventArgs e)
    {
        Console.WriteLine(e.Data);
    }

    // Handle Exited event and display process information.
    //private static void OnExited(object sender, System.EventArgs e)
    //{
    //    var process = sender as Process;
    //    if (process != null)
    //    {
    //        Console.WriteLine("ExitCode: " + process.ExitCode);
    //    }
    //    else
    //    {
    //        Console.WriteLine("Process exited");
    //    }
    //}
}
using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        var p = Process.Start(
            new ProcessStartInfo("git", "branch --show-current")
            {
                CreateNoWindow = true,
                UseShellExecute = false,
                RedirectStandardError = true,
                RedirectStandardOutput = true,
                WorkingDirectory = Environment.CurrentDirectory
            }
        );

        p.WaitForExit();
        string branchName =p.StandardOutput.ReadToEnd().TrimEnd();
        string errorInfoIfAny =p.StandardError.ReadToEnd().TrimEnd();

        if (errorInfoIfAny.Length != 0)
        {
            Console.WriteLine($"error: {errorInfoIfAny}");
        }
        else { 
            Console.WriteLine($"branch: {branchName}");
        }

    }
}