我有一个函数可以将从openFileDialog中选择的所有文件夹,子文件夹文件从一个位置复制到另一个位置:
我已经使这个功能复制了所有选定的路径:
public void CopiarFicheiros(string CopyTo, List<string> FilesToCopy )
{
foreach (var item in FilesToCopy)
{
string DirectoryName = Path.GetDirectoryName(item);
string Copy = Path.Combine(CopyTo, DirectoryName);
if (Directory.Exists(Copy) && DirectoryName.ToLower() != "newclient" && DirectoryName.ToLower() != "newservice")
{
Directory.CreateDirectory(Copy);
File.Copy(item, Copy + @"\" + Path.GetFileName(item), true);
}
else File.Copy(item, CopyTo + @"\" + Path.GetFileName(item), true);
}
}
逻辑充满了缺陷,而且我已经没时间了,而且似乎找不到合适的解决方案。
这是我从对话框中获取所选文件和文件夹的方法:
private List<string> GetFiles()
{
var Files = new List<string>();
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string sFileName = openFileDialog.FileName;
string[] arrAllFiles = openFileDialog.FileNames;
Files = arrAllFiles.ToList();
}
return Files;
}
有没有人有更好的解决方案或线索,我需要更改才能成功执行此操作? 非常感谢任何帮助,谢谢
答案 0 :(得分:0)
请勿使用OpenFileDialog
选择文件夹。顾名思义,它不是为了这项任务而做的。您希望FolderBrowserDialog
class执行此任务。
// Copy from the current directory, include subdirectories.
DirectoryCopy(".", @".\temp", true);
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}