CommandLine Parse Code Fragment

Command Line Parse Code Fragment

 

internal class CommandLine
    {
        /// <summary>
        /// get process command line info
        /// </summary>
        /// <param name="processId"></param>
        /// <returns>command line info, array length is 2, ex: ["C:\Windows\system32\svchost.exe","-k LocalService"]</returns>
        public static String[] GetCommandLineInfo(int processId)
        {
            String[] info = new string[2];
            info[0] = "";
            info[1] = "";
            //
            var commandLine = Wmi.GetCommandLine(processId);
            if (commandLine != "")
            {
                info = ParseCommandLine(commandLine);
            }
            return info;
        }

        /// <summary>
        /// get process command line info
        /// </summary>
        /// <param name="commandLine"></param>
        /// <returns>command line info, array length is 2, ex: ["C:\Windows\system32\svchost.exe","-k LocalService"]</returns>
        public static string[] ParseCommandLine(string commandLine)
        {
            string[] info = new String[2];

            //C:\Windows\system32\svchost.exe -k LocalService
            //"C:\Program Files (x86)\Avira\AntiVir Desktop\avgnt.exe" /min

            if (commandLine[0] == '"')
            {
                int end = commandLine.IndexOf('"', 1);
                if (end == -1)
                {
                    info[0] = commandLine;
                    info[1] = "";
                }
                else if (end + 1 < commandLine.Length)
                {
                    info[0] = commandLine.Substring(1, end + 1);
                    info[1] = commandLine.Substring(end + 1).TrimStart(' ');
                }
                else
                {
                    info[0] = commandLine;
                    info[1] = "";
                }
            }
            else
            {
                int pos = commandLine.IndexOf(' ');
                if (pos == -1)
                {
                    info[0] = commandLine;
                    info[1] = "";
                }
                else if (pos + 1 < commandLine.Length)
                {
                    info[0] = commandLine.Substring(0, pos);
                    info[1] = commandLine.Substring(pos + 1).TrimStart(' ');
                }
                else
                {
                    info[0] = commandLine;
                    info[1] = "";
                }
            }

            return info;
        }
    }

 

 

.