0

Hey.

I would like to save a txt file from the listbox into a folder that the user chooses.
I've got the writing to work, but so far it only saves the file to the debug folder (since I haven't specified another folder)

This is what I have so far:

private void saveListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
            this.folderBrowserDialog1.ShowNewFolderButton = true;
            this.folderBrowserDialog1.RootFolder = System.Environment.SpecialFolder.Desktop;
            DialogResult dr = this.folderBrowserDialog1.ShowDialog();
            

            if (dr == DialogResult.OK)
            {
                string foldername=this.folderBrowserDialog1.SelectedPath;

                StreamWriter sw = null;
                try
                {
                    sw = File.CreateText("test.txt");
                    sw.WriteLine("Saved on: " + DateTime.Now);
                    sw.WriteLine("");
                    foreach (object item in listBox1.Items)
                    {
                        sw.WriteLine(item.ToString());
                    }
                }
                catch (IOException k)
                {
                    MessageBox.Show(k.ToString());
                }
                catch (Exception s)
                {
                    MessageBox.Show(s.ToString());
                }
                finally
                {
                    if (sw != null)
                    {
                        sw.Close();
                    }
                }
            }
        }

so where do i put the foldername to make it save to that folder?

I know you can use saveFileDialog, but can't it be done this way too?

Thanks.

2
Contributors
2
Replies
4
Views
7 Years
Discussion Span
Last Post by ereruh
1

Use System.IO.Path to join two paths together.
In your case the selected folder and the hardcoded filename.
E.g.

string filename = Path.Combine(this.folderBrowserDialog1.SelectedPath, "test.txt");
...
sw = File.CreateText(filename);
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.