-3

Hello I'm attempting to take a user input for name and phone number and append it to my "phonebook", a .txt file like this: Katie Allen,555-1234 Jill Ammons,555-5678 Kevin Brown,555-9012 Elisa Garcia,555-3456 Jeff Jenkins,555-7890 Leo Killian,555-1122 Marcia Potemkin,555-3344 Kelsey Rose,555-5566

This is a multi - form application where users can search by name or number. This form requires that a name and number can be added to the txt file with a comma to delimit the two.

  private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            string name = nameTextBox.Text;
            string number = numberTextBox.Text;

            TextWriter tsw = new StreamWriter("PhoneList.txt", true);

            tsw.Write(name, number);




        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Currently when I run this form, I get the error "The process cannont access the file'......' because it is being used by another process"

In the main form this .txt file is being used to populate a listbox, I believe this is the issue. How can I resolve this?

Aaron Gasaway
  • 51
  • 1
  • 5
  • *"because it is being used by another process"* It think error message is clear... Close other apps using that file. (BTW: I am sure you'll say there isn't any other app using it) – Eser Dec 08 '15 at 22:06
  • Seems pretty clear right? Thanks for the helpful response.The app using it is the one that is running smart guy – Aaron Gasaway Dec 08 '15 at 22:07
  • Smart guy, don't forget to close the file you are using :) Where is *tsw* closed? – Eser Dec 08 '15 at 22:13
  • How can I close it if its being accessed on the main form to populate a listbox? I need to close it when the new form opens – Aaron Gasaway Dec 08 '15 at 22:17
  • It is problem of your coding logic. try to call *button1_Click* twice. boom:) – Eser Dec 08 '15 at 22:20

1 Answers1

0

You should close the stream when you done. The using block does it for you.

 try
    {
        string name = nameTextBox.Text;
        string number = numberTextBox.Text;

        using (TextWriter tsw = new StreamWriter("PhoneList.txt", true))
        {
            tsw.WriteLine(name + ", " + number);
        }




    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
Ilan
  • 624
  • 6
  • 11