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.

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);

That did the trick. Thank you very much! (y)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.