【问题标题】:Read from command line从命令行读取
【发布时间】:2018-04-26 16:07:50
【问题描述】:

我在阅读日期时遇到问题。任务:

目标是编写一个能够为特定文件构建和打印 Huffman 树的程序。程序将以单个命令行参数的形式接收文件名,从输入文件中读取所有数据并为该文件构建 Huffman 树...

例子:

$>program.exe simple.in

我的解决方案:

string FileName = Console.ReadLine();
fileBytes = File.ReadAllBytes(FileName);

但是这个解决方案写道:

RE:运行时错误 102:取消引用空值

谢谢

【问题讨论】:

  • 命令行参数通过args[]参数传递给Main函数。
  • 那么,我该怎么解决呢?不明白你的答案。
  • string filename = args[0]?这是假设你的主函数看起来像:private static void Main(string[] args),并且代码在那个方法中。
  • @FandaKožnar 您没有提供足够的代码示例或重现步骤的描述以供任何人帮助。你说你想从命令行读取,但你正在从控制台读取。但是后来你说它可以在你的机器上工作,但不能在学校工作。目前还不清楚你想要什么。人们建议使用教程,因为您的问题听起来像初学者。如果您想要更好的答案,请添加详细信息。
  • 你向我们展示的任何东西都没有让我觉得你不是初学者。

标签: c# file command-line arguments


【解决方案1】:

这应该让您开始从命令行阅读,但您需要对您尝试做的其余部分进行一些研究,并在您有特定问题时回来:

private static void Main(string[] args)
{
    Console.WriteLine($"The command line arguments entered are: {string.Join(" ", args)}");

    if (args.Length > 0)
    {
        var filePath = args[0];

        if (!File.Exists(filePath))
        {
            Console.WriteLine($"The specified file was not found: {filePath}");
        }
        else
        {
            // Process the file here
            var fileBytes = File.ReadAllBytes(filePath);
        }
    }
    else
    {
        Console.WriteLine(
            "Error: Enter the full path to a file as the first command line argument");
    }


    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

【讨论】:

    【解决方案2】:

    我解决了。 而不是:

    Console.ReadLine();
    

    我用过:

    args[0];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      • 1970-01-01
      • 1970-01-01
      • 2016-05-09
      • 2015-09-03
      • 2014-02-16
      相关资源
      最近更新 更多