Zebra0.com

csharp listboxList Box Editor: Step 6, Write to File from ListBox

List Box Editor: Step 6, Write to File from ListBox

Write to File from ListBox

Write the code for writefile as shown below. For now, you can call this from mnuSave.

private void writefile()
{
   // Filename is "Untitled" initially, on mnuNew and mnuSaveAs.
   if (currentFileName == "Untitled")
   {
      saveFileDialog1.Filter = "Text Files|*.txt|All Files|*.*";
      saveFileDialog1.ShowDialog();
      // Filename is "" if cancel selected. 
      if (saveFileDialog1.FileName != "")
      {
          currentFileName = saveFileDialog1.FileName;
          Text = currentFileName;
       }
    }  
    if (currentFileName!="Untitled")
    {
       using (System.IO.StreamWriter file =
          new System.IO.StreamWriter(currentFileName))
       {
          // Write each item in list box to file.
          foreach (string item in lstData.Items)
          {
             file.WriteLine(item);
          }
          file.Close();
          // We just saved, so no changes since last save.
          changed = false;
       }
   }
}

To Do: Call writefile from mnuSave. Make sure this works before proceeding.

NEXT: List Box Editor: Step 6, Write to File from ListBox