【问题标题】:Turn string into string array for command-line arguments将字符串转换为用于命令行参数的字符串数组
【发布时间】:2014-12-11 12:23:18
【问题描述】:

我有以下格式的字符串:

"arg1" "arg2" "arg3" ... "argx"

我将使用这个字符串作为我程序的命令行参数的string[]。 如何把这个字符串变成字符串数组?

【问题讨论】:

  • 使用任何可用的命令行解析器

标签: c# string command-line-arguments arrays


【解决方案1】:

自己实现所有的转义并不容易,尤其是CLR为你做的方式。

因此,您最好查看 CLR 源代码。 It mentionsCommandLineToArgvW api 有一个nice documentation

但我们是 C# 人,必须search this function signature here。幸运的是,它有一个很好的样本(我的样式):

internal static class CmdLineToArgvW
{
    public static string[] SplitArgs(string unsplitArgumentLine)
    {
        int numberOfArgs;
        var ptrToSplitArgs = CommandLineToArgvW(unsplitArgumentLine, out numberOfArgs);
        // CommandLineToArgvW returns NULL upon failure.
        if (ptrToSplitArgs == IntPtr.Zero)
            throw new ArgumentException("Unable to split argument.", new Win32Exception());
        // Make sure the memory ptrToSplitArgs to is freed, even upon failure.
        try
        {
            var splitArgs = new string[numberOfArgs];
            // ptrToSplitArgs is an array of pointers to null terminated Unicode strings.
            // Copy each of these strings into our split argument array.
            for (var i = 0; i < numberOfArgs; i++)
                splitArgs[i] = Marshal.PtrToStringUni(
                    Marshal.ReadIntPtr(ptrToSplitArgs, i * IntPtr.Size));
            return splitArgs;
        }
        finally
        {
            // Free memory obtained by CommandLineToArgW.
            LocalFree(ptrToSplitArgs);
        }
    }
    [DllImport("shell32.dll", SetLastError = true)]
    private static extern IntPtr CommandLineToArgvW(
        [MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine,
        out int pNumArgs);
    [DllImport("kernel32.dll")]
    private static extern IntPtr LocalFree(IntPtr hMem);
}

PS。请注意,可执行文件名称应该是该行中的第一个参数。

【讨论】:

    【解决方案2】:

    使用String.Split 方法在原始字符串上拆分字符串。

    如果您还需要删除引号,您可以遍历结果数组并获取不带引号的子字符串

    您也可以使用Regex.Split 一次性完成。

    【讨论】:

    • 拆分后你会得到损坏的参数。引号用于转义空格。引号本身用反斜杠转义。反斜杠用反斜杠转义。我不确定这就是全部。但你的回答是对问题的非常危险的简化
    猜你喜欢
    • 1970-01-01
    • 2017-11-27
    • 2011-06-18
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多