c# 将文件从文本框复制到选定目录

c# copy file from textbox to selected directory

我在 wpf 上使用 c#,运行 遇到一个问题,我 select 一些文件及其文件名进入了我的 'filespicked' 文本框。然后我有一个按钮应该将文件复制到另一个文件夹,与文本框中 selected 相同的文件。此按钮打开一个文件夹浏览器对话框,我 select 我想复制到的文件夹。

问题是,当我 select 文件夹并单击“确定”时,我的 try/catch 异常处理程序捕获了一个异常并且它没有复制。

这是我的代码。

private void Button_Click(object sender, RoutedEventArgs e)

    {
        FolderBrowserDialog dialog = new FolderBrowserDialog();
        dialog.Description = "Select a folder to copy to";
        dialog.ShowNewFolderButton = true;

        if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {

            string[] files = filePickedTextBox.Text.Split('\n');

            foreach (var file in files)
            {
                // Detect and handle the event of a non-valid filename
                try
                {
                    File.Copy(file, dialog.SelectedPath);
                }
                catch (Exception ex)
                {
                    outputTextBox.Text = ex.ToString();
                    return;
                }
            }
        }

这里是错误:

System.IO.IOException: 目标文件“C:\Users\tj\Desktop\copied_files”是目录,不是文件。 在 System.IO.File.InternalCopy(字符串 sourceFileName、字符串 destFileName、布尔值覆盖、布尔值 checkHost) 在 System.IO.File.Copy(字符串源文件名,字符串目标文件名) 在 WpfApp1.MainWindow.Button_Click(对象发送者,RoutedEventArgs e)

这个错误对我来说毫无意义,因为文件变量中的字符串是目标文件,而不是 copied_files 文件夹。那是目标文件夹。

复制目标必须是文件,而不是目录(因此“目标 文件...”)。如果要保留相同的文件名,请使用 Path.Combine 将文件名附加到 dialog.SelectedPath 上:

foreach (var file in files)
{
    // Detect and handle the event of a non-valid filename
    try
    {
        File.Copy(file, Path.Combine(dialog.SelectedPath, Path.GetFileName(file)));
    }
    catch (Exception ex)
    {
        outputTextBox.Text = ex.ToString();
        return;
    }
}