2016-11-25 45 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 
相關問題