2

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. How can I turn this string into a string array?

disasterkid
  • 6,948
  • 25
  • 94
  • 179

2 Answers2

0

It's not easy to implement all the escaping by yourself, especially in the way the CLR does for you.

So, you'd better look at CLR sources. It mentions CommandLineToArgvW api which has a nice documentation.

But we're C# guys and must search this function signature here. 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. Note, that executable name should be the first argument in the line.

astef
  • 8,575
  • 4
  • 56
  • 95
-1

Use the String.Split method to split the string on the original string.

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.

Marcobdv
  • 87
  • 3
  • After a split you'll get corrupted arguments. Quotation marks are used to escape spaces. Quotation marks by themselves are escaped with backslashes. And backslashes are escaped with backslashes. I'm not sure that's all. But your answer is a very dangerous simplification of a problem – astef Mar 10 '18 at 21:35