Vapenation Vapenation - 8 days ago 5
C# Question

How to pass a file path to the program via command line argument

I have 5 files, which I have parsed. They are text files, and I dont know how to pass them to the program via command line arguemnt. I am using visual studio, and C sharp. When I go into

Project>Properties>Debug>Command Line Argument>
Do I just type in the files? Like
File01.txt,File02.txt
etc...

Answer

The simplest way is to realise that command line arguments are passed to you as an array of strings in your Main(...) method.

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);
        }
    }
}

(Broadly from: https://msdn.microsoft.com/en-us/library/acy3edy3.aspx)

Specifically in answer to your question -- yes, in the debug tab, but they need to be space-separated, not comma separated.

If you actually want to open and read the files, you'll need something like (assuming they're text files):

int counter = 0;
string line;

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

(Broadly from: https://msdn.microsoft.com/en-GB/library/aa287535%28v=vs.71%29.aspx)

Comments