实时读取一个文本文件

本文关键字:一个 文本 文件 读取 实时 | 更新日期: 2023-09-27 18:11:31

在我的程序中实时读取一个文本文件,但我不能让它工作。下面是我的代码,没有错误:

  public void Main2(string[] args)
    {
        string[] fileContents;
        try
        {
            fileContents = File.ReadAllLines(@"C:'temp'log.txt");
            foreach (string line in fileContents)
            {
                Console.WriteLine(line);
            }
        }
        catch (FileNotFoundException ex)
        {
            throw ex;
        }
        catch (Exception e)
        {
            throw e;
        }
    }

控制台窗口不打印文本

实时读取一个文本文件

看不到任何输出的原因有两个:

    文件为空;
  1. 控制台窗口关闭之前,你看到任何出现在它。

第二个是我在你的代码中看到的唯一与代码相关的问题。您不必等到用户同意后才关闭控制台。

把它放在Main方法的末尾:

Console.ReadLine();

你需要按下enter关闭屏幕

我想到了两个原因:

  1. 不调用Main2()方法

启用断点并逐步执行

你的代码工作得很好,只是看到下面的代码更新了一件事,我在main函数的末尾添加了Console.ReadLine();,并且还将你的函数名称更改为Main2到main。你要按回车键控制台然后关闭屏幕。

更新代码:

static void Main(string[] args)
    {
        string[] fileContents;
        try
        {
            fileContents = File.ReadAllLines(@"C:'temp'log.txt");
            foreach (string line in fileContents)
            {
                Console.WriteLine(line);
            }
        }
        catch (FileNotFoundException ex)
        {
            throw ex;
        }
        catch (Exception e)
        {
            throw e;
        }
        //Here is my extra one line code            
        Console.ReadLine();
    }

注意:

确认您的文本文件是否存在。