Hmmm...TextReader suddenly stopped working...
I had this piece of code working just fine:
Code:
private void button1_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader("file.txt");
while (sr.Peek() >=0)
{
comboBox1.Items.Add(sr.ReadLine());
sr.Close();
}
}
But then suddenly, it starts giving me this error:
Cannot read from a closed TextReader.
Why this all of a sudden???
Complete code:
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace TrialAndError
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader("file.txt");
while (sr.Peek() >=0)
{
comboBox1.Items.Add(sr.ReadLine());
sr.Close();
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("Selected text: " + comboBox1.Text);
}
private void button2_Click(object sender, EventArgs e)
{
StreamWriter sw = File.AppendText("file.txt");
sw.Write(textBox1.Text);
sw.Close();
}
}
}
Re: Hmmm...TextReader suddenly stopped working...
You are closing the streamreader in each iteration. You should only close it after you are done peeking at the file:
Code:
private void button1_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader("file.txt");
while (sr.Peek() >=0)
{
comboBox1.Items.Add(sr.ReadLine());
}
sr.Close();
}
Re: Hmmm...TextReader suddenly stopped working...
Yeah i saw that after looking at the code intensively for 10 mins, but thx :D
Re: Hmmm...TextReader suddenly stopped working...
If you're using .NET 2.0 you should use File.ReadAllLines:
Code:
comboBox1.Items.AddRange(System.IO.File.ReadAllLines("file.txt"));
Either way you should always specify your version when posting.