Search
Module:
Directory

   Desktop Functions:

   Smart Device Functions:


Show Recent Changes
Subscribe (RSS)
Misc. Pages
Comments
FAQ
Helpful Tools
Playground
Suggested Reading
Website TODO List
Download Visual Studio Add-In

CommandLineToArgvW (shell32)
 
.
Summary

C# Signature:

[DllImport("shell32.dll", SetLastError = true)]
[DllImport("shell32.dll")]
static extern IntPtr CommandLineToArgvW(
   [MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine,
   out int pNumArgs);
   [MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine, out int pNumArgs);

VB.NET Signature:

Declare Function CommandLineToArgv Lib "shell32.dll" Alias "CommandLineToArgvW" ( _
    ByVal lpCmdLine As String, _
    ByRef pNumArgs As Integer) As Long

User-Defined Types:

None.

Notes:

Minimum DLL Version Shell32.dll version 6.0 or later
Minimum operating systems Windows NT Workstation 3.5, Windows NT Server 3.5, Windows 2000 Professional, Windows 2000 Server, Windows XP, Windows Server 2003
Unicode This function is implemented as Unicode.

Tips & Tricks:

Please add some!

Sample Code:

using System;
using System.Runtime.InteropServices;
using System.Text;

static class CmdLineToArgvW
namespace CmdLineToArgvW
{
    // The previous examples on this page used incorrect
    // pointer logic and were removed.

    static string[] SplitArgs(string unsplitArgumentLine)
    class MainModule
    {
        int numberOfArgs;
        IntPtr ptrToSplitArgs;
        string[] splitArgs;

        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
        static void Main(string[] args)
        {
            splitArgs = new string[numberOfArgs];
            Console.WriteLine( "args.Length: {0}", args.Length );
            for ( int i = 0; i < args.Length; i++ )
            {
                Console.WriteLine( "args[{0}]={1}", i, args[i] );
            }

            // ptrToSplitArgs is an array of pointers to null terminated Unicode strings.
            // Copy each of these strings into our split argument array.
            for (int i = 0; i < numberOfArgs; i++)
                splitArgs[i] = Marshal.PtrToStringUni(
                    Marshal.ReadIntPtr(ptrToSplitArgs, i * IntPtr.Size));
            Console.WriteLine();

            return splitArgs;
        }
        finally
        {
            // Free memory obtained by CommandLineToArgW.
            LocalFree(ptrToSplitArgs);
        }
    }
            int argc;
            IntPtr argvPtr = IntPtr.Zero;
            try
            {
                argvPtr = CommandLineToArgvW( Environment.CommandLine, out argc );
                // CommandLineToArgvW will list the executable as argv[0].
                // I want to see the same count as you get from "string[] args".
                Console.WriteLine( "argc: {0}", argc - 1 );

    [DllImport("shell32.dll", SetLastError = true)]
    static extern IntPtr CommandLineToArgvW(
        [MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine,
        out int pNumArgs);
                // argvPtr is a pointer to a pointer; dereference it
                IntPtr argPtr = Marshal.ReadIntPtr( argvPtr );

    [DllImport("kernel32.dll")]
    static extern IntPtr LocalFree(IntPtr hMem);
}
                for ( int i = 0; i < argc; i++ )
                {
                    string arg = Marshal.PtrToStringUni( argPtr );

                    // CommandLineToArgvW will list the executable as argv[0].
                    // I want to get the same output that "string[] args" yields,
                    // so I'll skip the output for i = 0
                    if ( i > 0 )
                    {
                        Console.WriteLine( "argv[{0}]={1}", i - 1, arg );
                    }

                    // Increment the pointer address by the number of Unicode bytes
                    // plus one Unicode character for the string's null terminator
                    int unicodeByteCount =
                        Encoding.Unicode.GetByteCount( arg ) +
                        Encoding.Unicode.GetByteCount( new char[] { Char.MinValue } );
                    argPtr = new IntPtr( argPtr.ToInt32() + unicodeByteCount );
                }

Alternative Managed API:

Do you know one? Please contribute it!

            }
            finally
            {
                LocalFree( argvPtr );
            }

Documentation

        }

        // Here's an wrapper to CommandLineToArgvW I found useful (csells@sellsbrothers.com)
        public static IEnumerable<string> CommandLineToExeAndArgs() {
            return CommandLineToExeAndArgs(Environment.CommandLine);
        }

        public static IEnumerable<string> CommandLineToExeAndArgs(string cmdline) {
            List<string> args = new List<string>();
            IntPtr argvPtr = IntPtr.Zero;

            try {
                int argc;
                argvPtr = CommandLineToArgvW(cmdline, out argc);

                // argvPtr is a pointer to a pointer; dereference it
                IntPtr argPtr = Marshal.ReadIntPtr(argvPtr);

                // CommandLineToArgvW will list the executable as argv[0]
                for( int i = 0; i < argc; i++ ) {
                    string arg = Marshal.PtrToStringUni(argPtr);
                    args.Add(arg);

                    // Increment the pointer address by the number of Unicode bytes
                    // plus one Unicode character for the string's null terminator
                    int unicodeByteCount = Encoding.Unicode.GetByteCount(arg) + Encoding.Unicode.GetByteCount(new char[] { Char.MinValue });
                    argPtr = new IntPtr(argPtr.ToInt32() + unicodeByteCount);
                }
            }
            finally {
                LocalFree(argvPtr);
            }

            return args;
        }

        [DllImport("shell32.dll")]
        static extern IntPtr CommandLineToArgvW(
            [MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine,
            out int pNumArgs);

        [DllImport("kernel32.dll")]
        static extern IntPtr LocalFree(IntPtr hMem);
    }
}

Alternative Managed API:

Do you know one? Please contribute it!

Documentation

On Windows Vista:

This API no longer works on windows Vista as Microsoft disabled it for security reasons. See http://msdn2.microsoft.com/en-us/library/ms647840.aspx.

Please edit this page!

Do you have...

  • helpful tips or sample code to share for using this API in managed code?
  • corrections to the existing content?
  • variations of the signature you want to share?
  • additional languages you want to include?

Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).

 
Access PInvoke.net directly from VS:
Terms of Use
Edit This Page
Find References
Show Printable Version
Revisions