Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How split this specific string into array

How can i split this specific string with spaces into array?
MyDatabase C:\MyDatabase\Backup "C:\Program Files\MySQL\MySQL Server 8.0\bin"

I want to have array like this: \

[MyDatabase], [C:\MyDatabase\Backup], ["C:\Program Files\MySQL\MySQL Server 8.0\bin"]

I can’t match any specific sperator for .Split() function

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you are writing code to parse command-line arguments, you could use the NuGet package System.CommandLine.

After adding that package, you can write code like this:

using System;
using System.CommandLine;

namespace Demo
{
    static class Program
    {
        static void Main()
        {
            string commandLine = "MyDatabase C:\\MyDatabase\\Backup \"C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\"";

            var cmd    = new RootCommand();
            var result = cmd.Parse(commandLine);

            Console.WriteLine($"{result.Tokens.Count} arguments found:");

            foreach (var argument in result.Tokens)
            {
                Console.WriteLine(argument);
            }
        }
    }
}

The output from that program is:

3 arguments found:
Argument: MyDatabase
Argument: C:\MyDatabase\Backup
Argument: C:\Program Files\MySQL\MySQL Server 8.0\bin

This is somewhat of a "sledgehammer to crack a nut", but if you really are parsing command line arguments, System.CommandLine provides a great deal of functionality beyond just the basic parsing.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading