从文本文件读取错误

穆斯塔法

因此,我有一个名为“ NEW.txt”的文本文件,我想从控制台窗口中读取其内容。我意识到有多种方法可以给猫咪剥皮,但是我正在尝试实现这一方法。

using (System.IO.StreamReader reader = new System.IO.StreamReader("NEW.txt"))
{
    String content = reader.ReadToEnd();
    Console.WriteLine(content);
}

但是我收到错误消息“ mscorlib.dll中发生了'System.ObjectDisposedException类型的未处理异常”

其他信息:无法写入已关闭的TextWriter。

什么是TextWriter?为什么关闭它?

更新:

       //using (System.IO.StreamWriter writer = new System.IO.StreamWriter("NEW.txt"))
       //     {
       //         System.Console.SetOut(writer);
       //         System.Console.WriteLine("Hello text file");
       //         System.Console.WriteLine("I'm writing to you from visual C#");
       //     }

       //This following part only works when the previous block is commented it out

        using (System.IO.StreamReader reader = new System.IO.StreamReader("NEW.txt"))
        {
            string content = reader.ReadToEnd();
            Console.WriteLine(content);

        }

假设问题是此行“ System.Console.SetOut(writer);” 如何将输出流更改回控制台窗口?

安德鲁·巴伯

这是您的代码。您注意到只有在注释顶部时它才起作用:

   //using (System.IO.StreamWriter writer = new System.IO.StreamWriter("NEW.txt"))
   //     {
   //         System.Console.SetOut(writer);
   //         System.Console.WriteLine("Hello text file");
   //         System.Console.WriteLine("I'm writing to you from visual C#");
   //     }

   //This following part only works when the previous block is commented it out

    using (System.IO.StreamReader reader = new System.IO.StreamReader("NEW.txt"))
    {
        string content = reader.ReadToEnd();
        Console.WriteLine(content);

    }

现在,您已经包括了要注释掉的代码,我在这里看到了问题……您正在将a设置StreamWriter为控制台的“输出”。然后关闭该StreamWriter窗口-关闭关联的窗口TextWriter然后,您稍后尝试再次使用它,从而导致错误:该TextWriter代码已关闭,因为您已使用该代码将其关闭。

要解决此问题,请更改您的注释代码以执行此操作:

   using (System.IO.StreamWriter writer = new System.IO.StreamWriter("NEW.txt"))
        {
            /* This next line is the root of your problem */
            //System.Console.SetOut(writer);

            /* Just write directly with `writer` */
            writer.WriteLine("Hello text file");
            writer.WriteLine("I'm writing to you from visual C#");
        }

没必要在Console这里进行。只需直接与作者联系即可。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章