c# 从文本文件中读取包含 CMD.EXE 命令的每一行并正确处理

c# read each line containing CMD.EXE comand from text file and process it correctly

我只需要一个具体的答案: 我能够创建一个文件,其中包含我需要的命令和选项,格式为每行所需的特定格式,例如:

@"C:\mydosprog\mydosprog.exe" -o=option1 -option2 
@"C:\mydosprog\mydosprog.exe" -o=option1 -option2 
@"C:\mydosprog\mydosprog.exe" -o=option1 -option2 
 ... and more lines

这是我使用的代码:

var launchmyfile = File.ReadAllLines(@"c:\foo\mycommands.txt");
       for (int i = 0; i < inputLines.Length; i++)
       System.Diagnostics.Process.Start(???????);
       //this is where i'm battling and at the ??'s :-)

有没有一种简单有效的方法来做到这一点? (类似于 dos 批处理文件,但在 c# 中) 如果是怎么办?

如果有任何提示、技巧和答案,我将不胜感激

谢谢

您迭代 inputLines 而不是 launchmyfile

但是您需要:

  • 从文件中删除 @ 符号,当它在字符串中并且在 Process.Start

    [=25 的路径中无效时,它与逐字装饰器一样没有意义=]
  • 保留引号,这些可以用来区分路径和命令行,您需要在程序中将它们分开


// test file
File.WriteAllLines(@"C:\TEMP\TEST.TXT", new string[] {
    @"""c:\windows\system32\ping.exe"" -n 3 google.com",
    @"""c:\windows\system32\ping.exe"" -n 3 google.com",
    @"""c:\windows\system32\ping.exe"" -n 3 google.com",
});

var launchmyfile = File.ReadAllLines(@"C:\TEMP\TEST.TXT");

for (int i = 0; i < launchmyfile.Length; i++)
{
    // 2nd " breaks the path from the command line
    int commandLinePos = launchmyfile[i].IndexOf("\"", 1);

    // get path
    string executable = launchmyfile[i].Substring(1, commandLinePos - 1);

    // get command line
    string commandLine = launchmyfile[i].Substring(commandLinePos + 2);

    // execute
    System.Diagnostics.Process.Start(executable, commandLine);
}