質問

Mono/.NETアプリから外部コマンドラインプログラムを実行したいと思います。たとえば、実行したいです メンコーダー. 。出来ますか:

  1. コマンドラインシェル出力を取得し、テキストボックスに書き込みますか?
  2. 数値を取得して、時間が経過した進行状況バーを表示するには?
役に立ちましたか?

解決

あなたがあなたを作成するとき Process オブジェクトセット StartInfo 適切に:

var proc = new Process 
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "program.exe",
        Arguments = "command line arguments to your executable",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

次に、プロセスを開始し、それから読み取ります。

proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
    string line = proc.StandardOutput.ReadLine();
    // do something with line
}

使用できます int.Parse() また int.TryParse() 文字列を数値に変換します。読んだ文字列に無効な数値文字がある場合、最初に文字列操作を行う必要がある場合があります。

他のヒント

出力を処理できます 同期して また 非同期.

1:同期の例

static void runCommand()
{
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/c DIR"; // Note the /c command (*)
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    process.Start();
    //* Read the output (or the error)
    string output = process.StandardOutput.ReadToEnd();
    Console.WriteLine(output);
    string err = process.StandardError.ReadToEnd();
    Console.WriteLine(err);
    process.WaitForExit();
}

ノート 両方を処理する方が良いこと 出力エラー: :それらは個別に処理する必要があります。

(*)いくつかのコマンドの場合(ここで StartInfo.Arguments)追加する必要があります /c 指令, それ以外の場合は、プロセスがフリーズします WaitForExit().

2:非同期の例

static void runCommand() 
{
    //* Create your Process
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/c DIR";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    //* Set your output and error (asynchronous) handlers
    process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
    process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
    //* Start process and handlers
    process.Start();
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();
    process.WaitForExit();
}

static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine) 
{
    //* Do your stuff with the output (write to console/log/StringBuilder)
    Console.WriteLine(outLine.Data);
}

出力を使用して複雑な操作を行う必要がない場合は、ハンドラーを直接インラインで追加するだけで、Outputhandlerメソッドをバイパスできます。

//* Set your output and error (asynchronous) handlers
process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
process.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data);

さて、エラーと出力の両方を読みたいが、他の回答(私のような)で提供されるソリューションのいずれかでデッドロックを取得する人のために、StandardOutputプロパティのMSDN説明を読んだ後に構築したソリューションがあります。

回答はT30のコードに基づいています。

static void runCommand()
{
    //* Create your Process
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/c DIR";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    //* Set ONLY ONE handler here.
    process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
    //* Start process
    process.Start();
    //* Read one element asynchronously
    process.BeginErrorReadLine();
    //* Read the other one synchronously
    string output = process.StandardOutput.ReadToEnd();
    Console.WriteLine(output);
    process.WaitForExit();
}

static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine) 
{
    //* Do your stuff with the output (write to console/log/StringBuilder)
    Console.WriteLine(outLine.Data);
}

これを行う標準.NETの方法は、プロセスから読むことです。 StandardOutput ストリーム。リンクされたMSDNドキュメントには例があります。同様に、あなたは読むことができます StandardError, 、そして書き込みます StandardInput.

  1. ここで説明するように、プロセスのコマンドラインシェル出力を取得することが可能です。 http://www.c-sharpcorner.com/uploadfile/edwinlima/systemdiagnosticprocess12052005035444am/systemdiagnosticprocess.aspx

  2. これはメンコーダーに依存します。コマンドラインにこのステータスを吸収する場合、はい:)

2つのプロセスに共有メモリを使用して通信できます。 MemoryMappedFile

主にメモリマップされたファイルを作成します mmf 「使用」ステートメントを使用した親プロセスでは、終了するまで2番目のプロセスを作成し、結果をに書き込ませます mmf 使用 BinaryWriter, 、次に、結果を読みます mmf 親プロセスを使用して、 mmf コマンドライン引数またはハードコードを使用して名前を付けます。

子プロセスでマッピングされたファイルを使用するときは、子プロセスがマッピングされたファイルに結果を書き込み、マッピングされたファイルが親プロセスでリリースされることを確認してください

例:親プロセス

    private static void Main(string[] args)
    {
        using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("memfile", 128))
        {
            using (MemoryMappedViewStream stream = mmf.CreateViewStream())
            {
                BinaryWriter writer = new BinaryWriter(stream);
                writer.Write(512);
            }

            Console.WriteLine("Starting the child process");
            // Command line args are separated by a space
            Process p = Process.Start("ChildProcess.exe", "memfile");

            Console.WriteLine("Waiting child to die");

            p.WaitForExit();
            Console.WriteLine("Child died");

            using (MemoryMappedViewStream stream = mmf.CreateViewStream())
            {
                BinaryReader reader = new BinaryReader(stream);
                Console.WriteLine("Result:" + reader.ReadInt32());
            }
        }
        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }

子プロセス

    private static void Main(string[] args)
    {
        Console.WriteLine("Child process started");
        string mmfName = args[0];

        using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting(mmfName))
        {
            int readValue;
            using (MemoryMappedViewStream stream = mmf.CreateViewStream())
            {
                BinaryReader reader = new BinaryReader(stream);
                Console.WriteLine("child reading: " + (readValue = reader.ReadInt32()));
            }
            using (MemoryMappedViewStream input = mmf.CreateViewStream())
            {
                BinaryWriter writer = new BinaryWriter(input);
                writer.Write(readValue * 2);
            }
        }

        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }

このサンプルを使用するには、2つのプロジェクトを含むソリューションを作成する必要があります。その後、子育てプロセスのビルド結果を%育児%/bin/debugから取得し、%parentdirectory%/bin/debugにコピーしてから実行してから実行します。親プロジェクト

childDirparentDirectory PCのプロジェクトのフォルダ名は幸運です:)

プロセスを起動する方法(バットファイル、Perlスクリプト、コンソールプログラムなど)、およびWindowsフォームに標準出力を表示する方法:

processCaller = new ProcessCaller(this);
//processCaller.FileName = @"..\..\hello.bat";
processCaller.FileName = @"commandline.exe";
processCaller.Arguments = "";
processCaller.StdErrReceived += new DataReceivedHandler(writeStreamInfo);
processCaller.StdOutReceived += new DataReceivedHandler(writeStreamInfo);
processCaller.Completed += new EventHandler(processCompletedOrCanceled);
processCaller.Cancelled += new EventHandler(processCompletedOrCanceled);
// processCaller.Failed += no event handler for this one, yet.

this.richTextBox1.Text = "Started function.  Please stand by.." + Environment.NewLine;

// the following function starts a process and returns immediately,
// thus allowing the form to stay responsive.
processCaller.Start();    

発見できる ProcessCaller このリンクで: プロセスを起動し、標準出力を表示します

Win and Linuxで私のために働いたソリューションはフォローです

// GET api/values
        [HttpGet("cifrado/{xml}")]
        public ActionResult<IEnumerable<string>> Cifrado(String xml)
        {
            String nombreXML = DateTime.Now.ToString("ddMMyyyyhhmmss").ToString();
            String archivo = "/app/files/"+nombreXML + ".XML";
            String comando = " --armor --recipient bibankingprd@bi.com.gt  --encrypt " + archivo;
            try{
                System.IO.File.WriteAllText(archivo, xml);                
                //String comando = "C:\\GnuPG\\bin\\gpg.exe --recipient licorera@local.com --armor --encrypt C:\\Users\\Administrador\\Documents\\pruebas\\nuevo.xml ";
                ProcessStartInfo startInfo = new ProcessStartInfo() {FileName = "/usr/bin/gpg",  Arguments = comando }; 
                Process proc = new Process() { StartInfo = startInfo, };
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.Start();
                proc.WaitForExit();
                Console.WriteLine(proc.StandardOutput.ReadToEnd());
                return new string[] { "Archivo encriptado", archivo + " - "+ comando};
            }catch (Exception exception){
                return new string[] { archivo, "exception: "+exception.ToString() + " - "+ comando };
            }
        }

以下のコードを使用して、プロセス出力をログに記録できます。

ProcessStartInfo pinfo = new ProcessStartInfo(item);
pinfo.CreateNoWindow = false;
pinfo.UseShellExecute = true;
pinfo.RedirectStandardOutput = true;
pinfo.RedirectStandardInput = true;
pinfo.RedirectStandardError = true;
pinfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
var p = Process.Start(pinfo);
p.WaitForExit();
Process process = Process.Start(new ProcessStartInfo((item + '>' + item + ".txt"))
{
    UseShellExecute = false,
    RedirectStandardOutput = true
});
process.WaitForExit();
string output = process.StandardOutput.ReadToEnd();
if (process.ExitCode != 0) { 
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top