除了 Process 之外,是否有任何其他替代方法可以在 C# 中执行内置 shell 命令

本文关键字:执行 命令 shell 内置 方法 之外 Process 是否 其他 任何 除了 | 更新日期: 2023-09-27 18:34:24

除了 Process 之外,还有其他方法可以在 C# 中执行内置的 shell 命令吗?目前我正在使用进程类来运行这些命令。但在当前场景中,我想并行运行 200 多个这样的命令。因此,生成 200 多个进程不是一个好主意。还有其他选择吗?

除了 Process 之外,是否有任何其他替代方法可以在 C# 中执行内置 shell 命令

"

运行dos命令"等同于"创建进程并运行它",因此即使有其他api,仍然会有200个进程(顺便说一下,除非您使用非常非常小的系统,否则无需担心)

你可以

但是,不应该这样做

using Microsoft.VisualBasic;
Interaction.Shell(...);

注意: 您必须添加对 VisualBasic 程序集的引用。

这是对您的问题的直接回答,但不是您应该做的事情。

正如Max Keller指出的那样,System.Diagnostics.Process总是启动一个新的系统进程。

如果必须启动进程/操作超过几秒钟,我宁愿将所有命令保存在临时文件中,并使用System.Diagnostics.Process而不是单个操作来执行。

// Get a temp file
string tempFilepath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "MyBatchFile.bat");
// Ensure the file dont exists yet
if (System.IO.File.Exists(tempFilepath)) {
    System.IO.File.Delete(tempFilepath);
}
// Create some operations
string[] batchOperations = new string[]{
    "START netstat -a",
    "START systeminfo"
};
// Write the temp file
System.IO.File.WriteAllLines(tempFilepath, batchOperations);
// Create process
Process myProcess = new Process();
try {
    // Full filepath to the temp file
    myProcess.StartInfo.FileName = tempFilepath;
    // Execute it
    myProcess.Start();
    // This code assumes the process you are starting will terminate itself!
} catch (Exception ex) {
    // Output any error to the console
    Console.WriteLine(ex.Message);
}
// Remove the temp file
System.IO.File.Delete(tempFilepath);