I want to pass a string array to main but keep spaces

与世无争的帅哥 提交于 2019-12-11 10:29:03

问题


I want to pass a string to main, but I am having trouble with spaces.

I pass the string "C:\Documents and Settings\desktop\..." to the Main(string[] args) and I had:

args[0] = "C:\Documents" 
args[1] = "and"
args[2] = "Settings\desktop\..."

But what I want is:

args[0] = "C:\Documents and Settings\desktop\..."

Any way to keep spaces but concatenate to one element of the string? The code should also work with any number of spaces in a given file path, not just 2 in this case.


回答1:


This is typically handled by passing the arguments in quotes.

For example, if you call this as:

yourApp.exe "C:\Documents and Settings\desktop..." 

You'll get the string in the first arg (args[0]).

For example, using this program:

using System;

internal class Program
{
    private static void Main(string[] args)
    {
        foreach (var arg in args) Console.WriteLine(arg);

        Console.ReadKey();
    }
}

If you run this with the command line argument as:

"C:\Documents and Settings\desktop..."

(With the quotation marks in place), this will print:

C:\Documents and Settings\desktop...

If that isn't an option, and you only have a single argument, you could always join the results:

using System;

internal class Program
{
    private static void Main(string[] args)
    {
        string argument = String.Join(" ", args);

        Console.WriteLine(argument);
        Console.ReadKey();
    }
}

This will work without wrapping the path in quotes, but it assumes the entire path is a single path, only has one space in between "words", and has no other arguments in place. Personally, I would recommend wrapping the call in quotation marks, as it's a standard convention.




回答2:


Can't you just quote the string when you call your program from the command line?

EXAMPLE: myprog "This is one argument"

namespace test
{
    class Program
    {
        /*
         * EXAMPLE: test arg1 "arg2 with spaces" arg3
         * args[0]=arg1...
         * args[1]=arg2 with spaces...
         * args[2]=arg3...
         */
        static void Main(string[] args)
        {
            for (int i = 0; i < args.Length; i++)
                System.Console.WriteLine("args[{0}]={1}...", i, args[i]);
        }
    }
}


来源:https://stackoverflow.com/questions/11889333/i-want-to-pass-a-string-array-to-main-but-keep-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!