Opening a text file is passed as a command line pa

2019-10-03 01:16发布

I need Console Application in C# which may open a .txt file like a parameter. I know only how to open a .txt file from root.

var text = File.ReadAllText(@"Input.txt");
Console.WriteLine(text);

3条回答
趁早两清
2楼-- · 2019-10-03 01:51

A starting point. Then what you want to do with the contents of the file is up to you

using System.IO;    // <- required for File and StreamReader classes

static void Main(string[] args)
{
    if(args != null && args.Length > 0)
    {
        if(File.Exists(args[0]))
        {
            using(StreamReader sr = new StreamReader(args[0]))
            {
                string line = sr.ReadLine();
                ........
            }
        }
    }
}

the above approach reads one line at a time to process the minimal quantity of text, however, if the file size is not a concert you could avoid the StreamReader object and use

        if(File.Exists(args[0]))
        {
            string[] lines = File.ReadAllLines(args[0]);
            foreach(string line in lines)
            {
                 ... process the current line
            }
        }
查看更多
劫难
3楼-- · 2019-10-03 01:59
void Main(string[] args)
{    
  if (args != null && args.Length > 0)
  {
   //Check file exists
   if (File.Exists(args[0])
   {
    string Text = File.ReadAllText(args[0]);
   }

  }    
}
查看更多
你好瞎i
4楼-- · 2019-10-03 02:02

here is a basic console aplication :

class Program
{
    static void Main(string[] args)
    {
        //Your code here
    }
}

The parameter args of the method Main is what you need, when you launch your program from a console you type in your program name and next to it your parameter( here the path to the txt file) Then to get it from the program just get it by args the first parameter is args[0] .

I hope it will help you

查看更多
登录 后发表回答