简体   繁体   中英

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!

These things are equivalent.

string targetPath = @"C:\TestFolder\"+ textBox1.Text;
string path = System.IO.Path.Combine(targetPath, textBox1.Text);

I would drop the first one for the Path.Combine call as it is portable and robust when it comes to the separators.

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

  • @"\\"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM