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

时间:2016-01-08 15:07:29

标签: c# file command

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

@"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#中) 如果是这样的话?

我会很感激任何提示和技巧和答案

谢谢

1 个答案:

答案 0 :(得分:1)

您迭代inputLines而不是launchmyfile

但是你需要:

  • 从文件中删除@符号,当它在字符串内部并且在Process.Start的路径中无效时,它与verbatim decorator一样无意义

  • 保留引号,这些可用于区分命令行和路径的路径。你需要在程序中将它们分开

// 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);
}     
相关问题