Reputation: 51
I'm working with c# on wpf and running into a problem where I select some files and their filenames go into my my 'filespicked' textbox. I then have a button that is supposed to copy the files, the same ones that were selected in the textbox, to another folder. This button opens up a folder browser dialog and I select the folder I want to copy to.
The problem is that when I select the folder and click ok, I get an exception caught by my try/catch exception handler and it does not copy.
Here is my code.
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;
}
}
}
And here is the error:
System.IO.IOException: The target file "C:\Users\tj\Desktop\copied_files" is a directory, not a file. at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost) at System.IO.File.Copy(String sourceFileName, String destFileName) at WpfApp1.MainWindow.Button_Click(Object sender, RoutedEventArgs e)
The error makes no sense to me because the string in the file variable is the target file, not the copied_files folder. That is the destination folder.
Upvotes: 0
Views: 344
Reputation: 11514
The copy destination needs to be a file, not a directory (Hence "The target file..."). Use Path.Combine to tack the file name onto dialog.SelectedPath if you want to keep the same file name:
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;
}
}
Upvotes: 2