2

我有一个字符串,其中包含一个可执行文件的路径,该文件中可能有也可能没有命令行参数。

例如:

"C:\Foo\Bar.exe"
"C:\Foo\Bar.exe /test"
"C:\Foo\Bar.exe {0}"
"C:\Foo\Bar.exe -snafu"

我正在尝试将字符串分解为路径部分和参数部分。参数部分几乎可以是任何格式。但是 IO.Path 函数假定字符串是一条没有争论的路径。例如,如果我打电话:

IO.Path.GetFileName(path)      

它返回Bar.exe /testBar.exe {0}Bar.exe -snafu

当我在命令提示符下运行它时,Windows 显然可以分辨出区别,因此必须有某种方法来利用现有功能。

如果需要,我可以用引号将字符串的路径部分括起来。但随后IO.Path通话失败。例如:

? IO.Path.GetFileName("""C:\Windows\write.exe"" {0}")

引发参数异常:路径中有非法字符。

4

2 回答 2

2

看看CommandLineToArgvW

于 2013-08-26T23:34:52.950 回答
1

CommandLineToArgvW将是 Sorceri 提到的最佳方法(您可以在此处查看示例代码),但这里有一个简单的实现可能就足够了。这假定将始终存在文件扩展名。

string input = @"C:\Foo\Bar test\hello.exe {0}";
string[] split = input.Split(' ');

int index = 0;
string ext = String.Empty;
string path = "";
string arguments = "";

while (true)
{
    string testPath = String.Join(" ", split, 0, index);
    ext = Path.GetExtension(testPath);
    if (!String.IsNullOrEmpty(ext))
    {
        path = Path.GetFullPath(testPath);
        arguments = input.Replace(path, "").Trim();
        break;
    }

    index++;
}

Console.WriteLine(path + " " + arguments);

您可以添加处理,以便在while未找到扩展名的情况下循环不会永远运行。我只使用您帖子中的三个 URL 对其进行了测试,因此您可能想要测试其他场景。

于 2013-08-26T23:57:47.600 回答