读取文本文件错误
本文关键字:错误 文件 取文本 读取 | 更新日期: 2023-09-27 18:08:30
所以我有一个名为"NEW.txt"的文本文件,我想从控制台窗口读取其内容。我意识到有不止一种方法来剥猫的皮,但我正试图实现这一个
using (System.IO.StreamReader reader = new System.IO.StreamReader("NEW.txt"))
{
String content = reader.ReadToEnd();
Console.WriteLine(content);
}
但是我得到的错误是"类型为'System '的未处理异常。ObjectDisposedException'发生在mscorlib.dll
附加信息:无法写入已关闭的文本写入器。"
什么是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);
}
现在你已经包含了你要注释掉的代码,我看到这里的问题…您正在将StreamWriter
设置为控制台的"Out"。然后闭合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
。直接和写信人一起写