How to use a txt file as command line argument?

2019-02-27 13:13发布

I have a .txt file like this:
6 4
1 2
2 3
3 4
4 5
1 2 4 5

How can I use this as command line argument in C#?

3条回答
爷的心禁止访问
2楼-- · 2019-02-27 13:36

You can accept the file name in the command line (along with path) and open the file in your application, read it line by line and process all the lines.

查看更多
等我变得足够好
3楼-- · 2019-02-27 13:49

If you intend to give your program data program.exe < data.txt, this is called reading from standard input. You can do this via .NET's Console.OpenStandardInput with

new StreamReader(Console.OpenStandardInput())

Alternatively, if you'd rather your program be run program.exe data.txt, start with

void Main(string[] args)
{
    File.ReadLines(args[0])
}
查看更多
你好瞎i
4楼-- · 2019-02-27 13:49

Go to Solution Explorer > Right click on project file > Select Properties from context menu. This opens the properties window of the project. Now Go to Debug tab > Go to Start options section in right pane. Put the full file path inside Command line arguments text box as shown below:

< "D:\Rasik\input01.txt"

enter image description here

Then you can write code as usual and you will start getting input from the file:

class Program
{        
    static void Main(string[] args)
    {
        var textInFirstLineOfFile = Console.ReadLine();
    }
}
查看更多
登录 后发表回答