除了Process之外还有其他替代方法可以在C#中执行内置的shell命令吗?

时间:2012-05-16 10:05:47

标签: c# command-line process

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

3 个答案:

答案 0 :(得分:2)

“运行dos命令”相当于“创建一个进程并运行它”,所以即使有另一个api,仍然会有200个进程(顺便说一下,除非你没有什么可担心的'依靠真正的真正的微小系统)

答案 1 :(得分:0)

你可以但不应该这样做

using Microsoft.VisualBasic;

Interaction.Shell(...);

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

这是你问题的直接答案,但不是你应该做的事情。

答案 2 :(得分:0)

正如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);