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.

Dani AI

Generated

As pointed out, the real issue is creating a full path from the folder the dialog returns and a filename instead of relying on the app's working directory. Below are a few practical, safer patterns and common pitfalls to close out the example that worked for .

A compact, robust write (creates folder if needed, timestamped filename, UTF‑8 encoding):

var folder = folderBrowserDialog1.SelectedPath;
if (string.IsNullOrWhiteSpace(folder)) return;

Directory.CreateDirectory(folder); // safe no-op if already exists

var fileName = "list_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".txt";
var fullPath = Path.Combine(folder, fileName);

File.WriteAllLines(fullPath,
    listBox1.Items.Cast<object>().Select(o => o.ToString()),
    Encoding.UTF8);

Notes and tips:

  • Directory.CreateDirectory is safe to call even if the folder exists; it avoids DirectoryNotFoundException.
  • Sanitize or validate dynamic filenames: check Path.GetInvalidFileNameChars and remove or replace them before building fileName.
  • Handle specific exceptions for clearer feedback: UnauthorizedAccessException (permissions), PathTooLongException, IOException (I/O errors). Present friendly messages rather than dumping stack traces.
  • For very large lists or long writes, run the I/O off the UI thread (Task.Run or async APIs) to keep the UI responsive.
  • If the user should pick the filename as well, the SaveFileDialog gives a better UX than FolderBrowserDialog; FolderBrowserDialog is appropriate when only the folder is needed.

These additions keep the fix that suggested but make the routine safer and more user-friendly in real applications.

Recommended Answers

All 2 Replies

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.