查看 C# 代码中的批处理 (.bat) 文件中的输出

本文关键字:文件 输出 bat 批处理 代码 查看 | 更新日期: 2023-09-27 18:37:18

我有一个 c# 代码来执行批处理文件。我想在命令提示符下显示 bat 文件中的信息。这是我新编辑的 c# 代码:

namespace CheckTime
{
class Program
{
    static void Main(string[] args)
    {
        Program Obj = new Program();
        int greetingId;
        int hourNow = System.DateTime.Now.Hour;
        if (hourNow < 12)
            greetingId = 0;
        else if (hourNow < 18)
            greetingId = 1;
        else
            greetingId = 2;
        System.Environment.ExitCode = greetingId;
        Obj.StartBatchFile(greetingId);

    }
   void StartBatchFile(int Gretting)
    {
        var p = new Process();
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.Arguments = string.Format(@"/C D:'Nimit Joshi'Visual Studio 2013'CheckTime'CheckTime'Demo1.bat {0}", Gretting);            
        p.OutputDataReceived += ConsumeData;

        try
        {
            p.Start();
            p.WaitForExit();
        }
        finally
        {
            p.OutputDataReceived -= ConsumeData;
        }
    }
    private void ConsumeData(object sender, DataReceivedEventArgs e)
    {
        Console.WriteLine(e.Data);
    }
 }

}

以下是我的 Demo1.bat 文件:

@echo off
:: Use %1 to get the first command line parameter
goto Greeting%1%
:Greeting
echo You have no entered a greeting.
goto end
:Greeting0
echo Good Morning
goto end
:Greeting1
echo Good Afternoon
goto end
:Greeting2
echo Good Evening
goto end
:end

它始终显示您没有输入问候语

查看 C# 代码中的批处理 (.bat) 文件中的输出

使用Process.OutputStream或收听Process.OutputDataReceived事件。

例:

private void ConsumeData(object sendingProcess, 
            DataReceivedEventArgs outLine)
{
    if(!string.IsNullOrWhiteSpace(outLine.Data))
        Console.WriteLine(outLine.Data);
}
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.OutputDataReceived += ConsumeData;
try
{
    p.Start();
    p.BeginOutputReadLine();
    p.WaitForExit();
}
finally
{
    p.OutputDataReceived -= ConsumeData;
}

应重写批处理文件,以免导致无限循环。

@echo off
:: Use %1 to get the first command line parameter
goto Greeting%1%
:Greeting
echo You have no entered a greeting.
goto end
:Greeting0
echo Good Morning
goto end
:Greeting1
echo Good Afternoon
goto end
:Greeting2
echo Good Evening
goto end
:end

C#

void StartBatchFile(int arg)
{
    var p = new Process();
    p.StartInfo.FileName = "cmd.exe";
    p.StartInfo.Arguments = string.Format(@"/C C:'temp'demo.bat {0}", arg);
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.CreateNoWindow = true;
    p.OutputDataReceived += ConsumeData;
    try
    {
        p.Start();
        p.BeginOutputReadLine();
        p.WaitForExit();
    }
    finally
    {
        p.OutputDataReceived -= ConsumeData;
    }
}

在调用 anotherMethod() 之前return(即退出程序)。

这很好,否则你会有一个无限循环的.exe盯着.bat.