views:

871

answers:

4

How can I save the contents of my listbox to a text file using a save file dialog?

I also want to add additional information to the text file and also add a message box saying saved when it's been successful.

Thankyou in advance for any help

A: 

To Save

   // fetch the selected Text from your list
   string textToRight = listBox1.SelectedItem.ToString();  

   // Write to a file       
   StreamWriter sr = File.CreateText(@"testfile.txt");       
   sr.Write(textToRight);
   sr.Close();

Message

   // display Message
   MessageBox.Show( "Information Saved Successfully" ); 
Asad Butt
**You forgot to close your StreamWriter**.
SLaks
have fixed, thanks.
Asad Butt
+1  A: 

A SaveFileDialog is used with ShowDialog() to show it to the user, and if it's successful, using its OpenFile() to get the (File)Stream that you write to. There's an example on the msdn page.

A ListBox can be accessed through its Items property, which is simply a collection of the items on it.

Tanzelax
A: 

You have a few things going on there - make sure you split them up, e.g.

  • Get list box contents
  • Append Info
  • Write File

Please note!! There is a myriad of exceptions you can get while saving a file, see the docs and handle them somehow...

// Get list box contents
var sb = new StringBuilder();
foreach (var item in lstBox.Items)
{
    // i am using the .ToString here, you may do more
    sb.AppendLine(item);
}
string data = sb.ToString();

// Append Info
data = data + ????....

// Write File
void Save(string data)
{
    using(SaveFileDialog saveFileDialog = new SaveFileDialog())
    {
        // optional
        saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);

        //saveFileDialog.Filter = ???;

        if (saveFileDialog.ShowDialog() == DialogResult.OK)
        {
            File.WriteAllText(saveFileDialog.Filename);
            MessageBox.Show("ok", "all good etc");
        }
        else
        {
        // not good......
        }
    }
}
Paul Kohler
fix your code block formatting, please... ;)
dboarman
yeah - that was ugly! (done)
Paul Kohler
A: 

this should do it.

private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog f = new OpenFileDialog();

    f.ShowDialog();                 

    ListBox l = new ListBox();
    l.Items.Add("one");
    l.Items.Add("two");
    l.Items.Add("three");
    l.Items.Add("four");

    string textout = "";

    // assume the li is a string - will fail if not
    foreach (string li in l.Items)
    {
        textout = textout + li + Environment.NewLine;
    }

    textout = "extra stuff at the top" + Environment.NewLine + textout + "extra stuff at the bottom";
    File.WriteAllText(f.FileName, textout);

    MessageBox.Show("all saved!");
}
nbushnell