Opening a text file is passed as a command line parameter [closed]

寵の児 提交于 2019-12-14 03:38: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);

回答1:


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



回答2:


void Main(string[] args)
{    
  if (args != null && args.Length > 0)
  {
   //Check file exists
   if (File.Exists(args[0])
   {
    string Text = File.ReadAllText(args[0]);
   }

  }    
}



回答3:


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



来源:https://stackoverflow.com/questions/16710152/opening-a-text-file-is-passed-as-a-command-line-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!