Jonathan Crispe

Jonathan Crispe

  • NA
  • 46
  • 48.4k

TextFile

Oct 2 2011 11:01 PM

my new task:
*A text file of bookmarks will be loaded into the listbox. If the text file does not exist, or an exception occurred, a messagebox will be used to display an error message.

i did what he asked and is in "Form1_Load" but everytime i open the program the list i have says "System.IO.StreamReader".
and when i close it gives me warning: "The process cannot access the file because it is being used by another process.
This warning doesn't pop if i bookmark(add) some website to my listbox.

here is my code:


  private void btn_go_Click(object sender, EventArgs e)
  {
  wBrowser.Navigate(tbx_website.Text);
  }

  private void btn_bookmark_Click(object sender, EventArgs e)
  {
  //Add the url to the listbox
  LBlist.Items.Add(tbx_website.Text);
  }

  private void btn_delete_Click(object sender, EventArgs e)
  {
  // The Delete button was clicked
  int i_delete = LBlist.SelectedIndex;
 
  try
  {
  // Remove the item in the List.
  LBlist.Items.RemoveAt(i_delete);

  if (LBlist.Items.Count == 0)
  {
  btn_delete.Enabled = false;
  }
  }
  catch
  {
  }
  }

  private void listbox_DoubleClick(object sender, EventArgs e)
  {
  wBrowser.Navigate(LBlist.SelectedIndex.ToString());
 
  }

  private void wBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
  {
  tbx_website.Text = wBrowser.Url.ToString();
  }

  private void LBlist_SelectedIndexChanged(object sender, EventArgs e)
  {
  if (LBlist.Items.Count == 0)
  {
  btn_delete.Enabled = false;
  }
  }
  private void Form1_Load(object sender, EventArgs e)
  {
  // test to exists 'bookmarks.txt' in the current path
  if (File.Exists("bookmarks.txt"))
  {
  StreamReader sr = new StreamReader("bookmarks.txt");  
  foreach (string item in sr.ToString().Split(new char[] { ';' })) LBlist.Items.Add(item);
  }
  else
  {
  MessageBox.Show("No found the file!");
  }
  btn_delete.Enabled = false;
  }
  private void Form1_FormClosed(object sender, FormClosedEventArgs e)
  {
  StreamWriter sw_file;
  string s_bmfile = "";
  foreach (object item in LBlist.Items) s_bmfile += item.ToString() + ";";
  try
  {
  sw_file = new StreamWriter("bookmarks.txt");
  sw_file.Write(s_bmfile); sw_file.Close();
  }
  catch (Exception ex)
  {
  MessageBox.Show(ex.Message);
  }
  }

Answers (5)