[英]How to copy selected folders, subfolders and files from openFileDialog in c#
I have a function that is suposed to copy all folders, subfolders files selected from openFileDialog from a location to another: 我有一个函数可以将所有文件夹,从openFileDialog选择的子文件夹文件从一个位置复制到另一个位置:
I've made this function to copy all the selected paths: 我已经制作了此函数来复制所有选定的路径:
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);
}
}
The logic is full of flaws and I'm running out of time and can't seem to find a proper solution to this. 逻辑充满了缺陷,我的时间不多了,似乎无法找到适当的解决方案。
This is how I get the selected files and folders from the dialog: 这是我从对话框中获取所选文件和文件夹的方式:
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;
}
Does anyone have a better solution or a clue to what I need to change to successfully do this? 有没有人有更好的解决方案或我需要更改以成功完成此操作的线索? Any help is highly appreciated, thank you
任何帮助表示高度赞赏,谢谢
Don't use OpenFileDialog
to choose the folder. 不要使用
OpenFileDialog
选择文件夹。 As the name suggests, it not made for that task. 顾名思义,它不是完成该任务的。 You want the
FolderBrowserDialog
class for this task. 您需要此任务的
FolderBrowserDialog
类 。
How to: Copy Directories : 如何:复制目录 :
// 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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.