in c# Read full txt file

I tried to do a form application and I have a problem about use StreamReader feature. in StreamWriter feature, I did it but StreamReader just read the last line and The txt file contains, in many rows for example: names and phone numbers but like I said the code read last line

    private void button2_Click(object sender, EventArgs e)
    {
        //1

        StreamWriter sw;
        sw = File.AppendText("metinbelgesi.txt");
       sw.Write(textBox1.Text + " ");
        sw.Write(textBox2.Text + " ");
        sw.WriteLine(textBox3.Text+"." );


        sw.Flush();
        sw.Close();

    }

    private void button3_Click(object sender, EventArgs e)
    {

        if (File.Exists("metinbelgesi.txt"))
        {
             FileStream fs = new FileStream("metinbelgesi.txt", FileMode.Open, FileAccess.Read);
            StreamReader sw = new StreamReader(fs);

            //sw = File.AppendText("metinbelgesi.txt");
            string yazi = sw.ReadLine();
            while (yazi != null)
            {

                richTextBox1.Text = yazi;

            }

            sw.Close();
            fs.Close();
        }
        else
        {
            MessageBox.Show("First, You Join.");

        }
    }

What do I do?

Upvotes: 0

Views: 149

Answers (3)

Enigmativity
Enigmativity

Reputation: 117057

You should probaby try to make your life easier by using some of the simpler File operations.

Try this instead:

private void button2_Click(object sender, EventArgs e)
{
    File.AppendAllText("metinbelgesi.txt", $"{textBox1.Text} {textBox2.Text} {textBox3.Text}.");
}

private void button3_Click(object sender, EventArgs e)
{
    if (File.Exists("metinbelgesi.txt"))
    {
        richTextBox1.Text = File.ReadAllText("metinbelgesi.txt");
    }
    else
    {
        MessageBox.Show("First, You Join.");
    }
}

Upvotes: -1

Frederik Gheysels
Frederik Gheysels

Reputation: 56934

According to your code, you're only reading the first line. There should be a ReadLine() statement inside your loop as well.

Pay attention that you will always overwrite the contents of the textbox with the line of text you've just read. So, when you've finished your loop, only the last line that you've read will occur in the textbox.

For simplicity, you can also have a look at the File class and more specifically the ReadAllLines() method.

Upvotes: 2

IAmCoder
IAmCoder

Reputation: 3442

You are reading it line by line and keep overwriting richTextBox1 with the next line... try:

richTextBox1.Text = "";
while (yazi != null)
{
    richTextBox1.Text += yazi;
    yazi = sw.ReadLine();
}

Or, if you don't need to parse each line, you can read it all in one go:

if (File.Exists("metinbelgesi.txt"))
{
    richTextBox1.Text = File.ReadAllText("metinbelgesi.txt");
}

Upvotes: 2

Related Questions