C# 将字符串转换为命令行参数的字符串数组

C# 将字符串转换为命令行参数的字符串数组,c#,string,command-line-arguments,arrays,C#,String,Command Line Arguments,Arrays,我有以下格式的字符串: "arg1" "arg2" "arg3" ... "argx" 我将使用这个字符串作为程序命令行参数的字符串[]。 如何将此字符串转换为字符串数组?使用此方法在原始字符串上拆分字符串 如果您还需要删除引号,您可以循环遍历生成的数组并获得不带引号的子字符串 或者,您可以使用一次完成。单独实现所有转义并不容易,尤其是在CLR为您提供的方式中 所以,您最好查看CLR源。CommandLineToArgvW api,该api具有 但我们是C族,必须这样。幸运的是,它有一个很好的

我有以下格式的字符串:

"arg1" "arg2" "arg3" ... "argx"
我将使用这个字符串作为程序命令行参数的字符串[]。 如何将此字符串转换为字符串数组?

使用此方法在原始字符串上拆分字符串

如果您还需要删除引号,您可以循环遍历生成的数组并获得不带引号的子字符串


或者,您可以使用一次完成。

单独实现所有转义并不容易,尤其是在CLR为您提供的方式中

所以,您最好查看CLR源。CommandLineToArgvW api,该api具有

但我们是C族,必须这样。幸运的是,它有一个很好的我的风格样本:

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);
}

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

使用任何可用的命令行解析器进行拆分,您将得到损坏的参数。引号用于转义空格。引号本身用反斜杠转义。反斜杠用反斜杠转义。我不确定就这些。但你的答案是一个非常危险的问题简化