Search code examples
c#multi-selectopenfiledialog

OpenFileDialog multiselect targetpath from textbox


Hy everyone,

I would like to copy multiple selected files with openfiledialog to a folder which is defined as @"C:\TestFolder\"+ textBox1.Text. My problem is that somehow the program writes the textBox content in the file name too.

Please find below my code:

private void button3_Click(object sender, EventArgs e)
{
    OpenFileDialog od = new OpenFileDialog();
    od.Filter = "All files (*.*)|*.*";
    od.Multiselect = true;
    if (od.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        string targetPath = @"C:\TestFolder\"+ textBox1.Text;
        string path = System.IO.Path.Combine(targetPath, textBox1.Text);

        if (!System.IO.Directory.Exists(targetPath)
        {
            System.IO.Directory.CreateDirectory(targetPath);
        } 
        foreach (string fileName in od.FileNames)
        {            
            System.IO.File.Copy(fileName, path + System.IO.Path.GetFileName(fileName));
        } 
    }
}

Any input would be appreciated!


Solution

  • Try this one:

     string Main_dir = @"C:\TestFolder\";
     string Sub_dir = textBox1.Text + @"\";
     string targetPath = System.IO.Path.Combine(Main_dir, Sub_dir);
          {
               if (!System.IO.Directory.Exists(targetPath))
          {
               System.IO.Directory.CreateDirectory(targetPath);
          }
               foreach (string fileName in od.FileNames)
    
               System.IO.File.Copy(fileName, targetPath + System.IO.Path.GetFileName(fileName), true);
          }
    

    Backslash is missing

    • @"\"