如何使用批处理文件C#

问题描述 投票:0回答:2

我有一个名为的文件(示例),如果您执行它要求提示“test”的文件,那么它会输出“testtest”

我如何监控批处理文件的输出,以及如何进行输入。

c# windows batch-file
2个回答
0
投票

您需要重定向进程的输入和输出:

using System;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;

namespace ProcessStandardInputSample
{
    class StandardInputTest
    {
        static void Main()
        {
            Console.WriteLine("Ready to sort one or more text lines...");

            // Start the Sort.exe process with redirected input.
            // Use the sort command to sort the input text.
            using (Process myProcess = new Process())
            {
                myProcess.StartInfo.FileName = "Sort.exe";
                myProcess.StartInfo.UseShellExecute = false;
                myProcess.StartInfo.RedirectStandardInput = true;

                myProcess.Start();

                StreamWriter myStreamWriter = myProcess.StandardInput;

                // Prompt the user for input text lines to sort.
                // Write each line to the StandardInput stream of
                // the sort command.
                String inputText;
                int numLines = 0;
                do
                {
                    Console.WriteLine("Enter a line of text (or press the Enter key to stop):");

                    inputText = Console.ReadLine();
                    if (inputText.Length > 0)
                    {
                        numLines++;
                        myStreamWriter.WriteLine(inputText);
                    }
                } while (inputText.Length > 0);

                // Write a report header to the console.
                if (numLines > 0)
                {
                    Console.WriteLine($" {numLines} sorted text line(s) ");
                    Console.WriteLine("------------------------");
                }
                else
                {
                    Console.WriteLine(" No input was sorted");
                }

                // End the input stream to the sort command.
                // When the stream closes, the sort command
                // writes the sorted text lines to the
                // console.
                myStreamWriter.Close();

                // Wait for the sort process to write the sorted text lines.
                myProcess.WaitForExit();
            }
        }
    }
}

0
投票

这可能对你有帮助

    ProcessStartInfo processInfo;
Process process;

processInfo = new ProcessStartInfo("path to batch" );
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;

processInfo.RedirectStandardOutput = true;

process = Process.Start(processInfo);
string output = process.StandardOutput.ReadToEnd();
Console.WriteLine(output);
process.WaitForExit();

process.Close();
© www.soinside.com 2019 - 2024. All rights reserved.