简体   繁体   English

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

[英]Turn string into string array for command-line arguments

I have string with the following format: 我有以下格式的字符串:

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

I am going to use this string as the string[] for my program's command-line arguments. 我将使用此字符串作为程序命令行参数的string[] How can I turn this string into a string array? 如何将此字符串转换为字符串数组?

Use the String.Split method to split the string on the original string. 使用String.Split方法将字符串拆分为原始字符串。

if you need to remove the Quotation marks as well you could either loop through the resulting array and getting the substrings without the quotation marks 如果还需要删除引号,则可以遍历结果数组并获取不带引号的子字符串

Alternatively you could use the Regex.Split to do it in one go. 另外,您也可以使用Regex.Split一次性完成。

It's not easy to implement all the escaping by yourself, especially in the way the CLR does for you. 自己实现所有转义并不容易,尤其是CLR为您完成的方式。

So, you'd better look at CLR sources. 因此,您最好查看CLR来源。 It mentions CommandLineToArgvW api which has a nice documentation . 它提到了 CommandLineToArgvW api,它有一个不错的文档

But we're C# guys and must search this function signature here . 但是我们是C#专家,必须在这里搜索此函数签名 Luckily, it has a good sample (my styling): 幸运的是,它有一个很好的示例(我的样式):

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. PS。 Note, that executable name should be the first argument in the line. 注意,可执行文件名应该是该行的第一个参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM