2016-11-25 48 views
-3

我有5个文件,我已经解析。他们是文本文件,我不知道如何通过命令行arguemnt将它们传递给程序。我正在使用visual studio,而C sharp。当我进入Project>Properties>Debug>Command Line Argument>时是否只需键入文件?像File01.txt,File02.txt等...如何通过命令行参数传递文件路径到程序

+0

你想告诉文件(可能与路径)的程序的* *的名字,让它打开它们,或者管的内容到程序? – doctorlove

+0

你的意思是解析或传递 - 就像有人把文件传给你一样? –

+0

蒂姆巴拉斯 - 我的意思是解析。我有5个预定义的文本文件,我已成功解析没有问题。我只是无法理解如何通过命令行参数将文件路径传递给程序。 – Vapenation

回答

5

最简单的方法是实现将命令行参数作为Main(...)方法中的字符串数组传递给您。

class TestClass 
{ 
    static void Main(string[] args) 
    { 
     // Display the number of command line arguments: 
     System.Console.WriteLine(args.Length); 

     foreach(var arg in args) 
     { 
      System.Console.WriteLine(arg); 
     } 
    } 
} 

(广义来自:https://msdn.microsoft.com/en-us/library/acy3edy3.aspx

具体来说,在回答你的问题 - 是的,在调试选项卡,但他们需要用空格分开的,而不是逗号分隔。

如果你真的想打开并阅读这些文件,你需要像(假设他们是文本文件):

int counter = 0; 
string line; 

using(var file = new System.IO.StreamReader(arg)) 
{ 
    while((line = file.ReadLine()) != null) 
    { 
     Console.WriteLine (line); 
     counter++; 
    } 
} 

(广义来自:https://msdn.microsoft.com/en-GB/library/aa287535%28v=vs.71%29.aspx

+2

注意,如果一个参数包含空格,则应该用引号,即““我的论点”'包围 – TheLethalCoder

0

在主方法,您可以通过以下方式处理您的论点:

static void Main(string[] args) 
{ 
    if (args.Length > 0) 
    { 
     foreach (string p in args) 
     { 
      Console.WriteLine(p); 
     } 
    } 
    else 
    { 
     Console.WriteLine("Empty input parameters"); 
    } 
} 

当你运行命令行程序,必须使用以下语法:

C:\>yourprogram.exe firstfile.txt secondfile.xls thridfile.dat 
相关问题