简体   繁体   中英

C# Loading a file from a command line?

I am relatively new to C# and I am having a little trouble.

I am creating a program where I want to load a file from the command line. For example:

MyProgram.exe C:\ExcelDocument.xls

in the Main method of your program the args string array parameter to the method will contain any command line parameters. The args array will contain 1 value for each space separated element that is not enclosed in quotes (")

so

myprograme.exe c:\my documents\file1.xls 

will result in 2 args:

c:\my
documents\file1.xls

whereas

myprograme.exe "c:\my documents\file1.xls"

will result in 1 value in args:

c:\my documents\file1.xls

you can access the params via the indexer:

string file = args[0];

assuming that the file is the first argument.

obviously you will still need to load the actual file, this will only give you the name give as a parameter to your program.

you can retrieve the file by using args[0].

public static void Main(string [] args)
{
    //This will print the first argument you passed in on command line.
    Console.WriteLine(args[0]); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM