简体   繁体   English

C# 从命令行加载文件?

[英]C# Loading a file from a command line?

I am relatively new to C# and I am having a little trouble.我对 C# 比较陌生,遇到了一些麻烦。

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.在程序的Main方法中,该方法的args字符串数组参数将包含任何命令行参数。 The args array will contain 1 value for each space separated element that is not enclosed in quotes (") args 数组将为每个未用引号 (") 括起来的空格分隔元素包含 1 个值

so所以

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

will result in 2 args:将产生 2 个参数:

c:\my
documents\file1.xls

whereas然而

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

will result in 1 value in args:将在 args 中产生 1 个值:

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].您可以使用 args[0] 检索文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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