在 C# 中运行批处理脚本
作者:迹忆客
最近更新:2023/08/12
浏览次数:
在本文中,我们将了解如何编写可以从目录运行批处理文件的 C# 程序。
在 C# 中运行批处理脚本
在C#中,当我们想要执行一个批处理文件时,它充当一个进程。 您可以按照下面的示例代码使用 C# 程序运行批处理脚本。
System.Diagnostics.Process pros = new System.Diagnostics.Process();
pros.StartInfo.FileName = "C:\\MyDir\\simple.bat";
pros.StartInfo.WorkingDirectory = "C:\\MyWorkDir";
pros.Start();
在上面的示例代码中,我们执行一个名为 simple.bat 的批处理脚本。 在这里,您需要在开始该过程之前设置工作目录。
上面的示例是可以从指定目录运行批处理文件的代码段。 在下面的代码片段中,我们很快执行了相同的任务。
代码-C#:
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
namespace BatchLoader
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button_Click(object sender, EventArgs e)
{
// initialize empty process
Process pros = null;
try
{
string BatFileDir = string.Format(@"D:\"); // directory of the file
pros = new Process();
pros.StartInfo.WorkingDirectory = BatFileDir;
pros.StartInfo.FileName = "Mybat.bat"; // batch file name to be execute
pros.StartInfo.CreateNoWindow = false;
pros.Start(); // run batch file
pros.WaitForExit();
MessageBox.Show("Batch file successfully executed !!");
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace.ToString());
}
}
}
}
首先,我们将所有必需的包初始化为我们的代码。 然后我们初始化所有的图形组件。
我们提供通过按钮运行批处理文件的操作。 通过 Process pros = null;
行,我们初始化一个空进程。
我们将代码的主要部分保留在异常处理程序中,因为它可能会生成运行时错误。 通过行 string BatFileDir = string.Format(@"D:\");
我们获取一个包含文件目录的字符串。
之后,我们声明了一个新进程并使用变量 BatFileDir 初始化了工作目录。 我们通过 pros.StartInfo.FileName = "Mybat.bat"; 行设置文件名; 并通过 pros.StartInfo.CreateNoWindow = false;
行禁用打开新窗口。
然后我们通过 pros.Start();
行执行批处理文件。 行 pros.WaitForExit();
让程序等待,直到完成批处理文件的执行。
最后,我们通过 MessageBox.Show(“Batch file successfully executed !!”);
向用户显示批处理文件已成功执行的消息。