【问题标题】:Opening a text file is passed as a command line parameter [closed]打开文本文件作为命令行参数传递[关闭]
【发布时间】:2013-05-18 14:09:43
【问题描述】:

我需要 C# 中的控制台应用程序,它可以像参数一样打开一个 .txt 文件。 我只知道如何从根目录打开 .txt 文件。

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

【问题讨论】:

  • 你说给我写
  • 对直线度感到抱歉

标签: c# command-line console-application


【解决方案1】:

一个起点。那么你想对文件的内容做什么取决于你

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

上述方法一次读取一行以处理最少数量的文本,但是,如果文件大小不是一个音乐会,您可以避免使用 StreamReader 对象并使用

        if(File.Exists(args[0]))
        {
            string[] lines = File.ReadAllLines(args[0]);
            foreach(string line in lines)
            {
                 ... process the current line
            }
        }

【讨论】:

  • 如何选择需要的文件?
  • 您在应用程序启动时将文件名作为参数传递,例如:yourApp.exe yourfilename.txt。如果您想在应用程序已经运行时向用户询问文件名,请查看Console.ReadLine
  • 谢谢,但是,我必须把我的 .txt 文件放在哪里?
【解决方案2】:

这是一个基本的控制台应用程序:

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

方法 Main 的参数 args 是您所需要的,当您从控制台启动程序时,您输入您的程序名称并在它旁边输入您的参数(这里是 txt 文件的路径) 然后要从程序中获取它,只需通过 args 获取它,第一个参数是 args[0] 。

希望对你有帮助

【讨论】:

  • +1 因为这正是 OP 要求的。 C# 中的控制台应用程序可能(也可能不会)打开 .txt。 ^_^
【解决方案3】:
void Main(string[] args)
{    
  if (args != null && args.Length > 0)
  {
   //Check file exists
   if (File.Exists(args[0])
   {
    string Text = File.ReadAllText(args[0]);
   }

  }    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 2018-03-20
    • 2012-01-06
    • 2012-09-24
    • 2012-12-21
    • 2015-09-12
    • 1970-01-01
    相关资源
    最近更新 更多