复制主文件夹
private void CopyDirectory(string srcdir, string desdir) { try { if (File.Exists(srcdir)) { File.Copy(srcdir, desdir); } else { string folderName = srcdir.Substring(srcdir.LastIndexOf("\\") + 1); string desfolderdir = desdir + "\\" + folderName; if (desdir.LastIndexOf("\\") == (desdir.Length - 1)) { desfolderdir = desdir + folderName; } string[] filenames = Directory.GetFileSystemEntries(srcdir); foreach (string file in filenames)// 遍历所有的文件和目录 { if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件 { string currentdir = desfolderdir + "\\" + file.Substring(file.LastIndexOf("\\") + 1); if (!Directory.Exists(currentdir)) { Directory.CreateDirectory(currentdir); } CopyDirectory(file, desfolderdir); } else // 否则直接copy文件 { string srcfileName = file.Substring(file.LastIndexOf("\\") + 1); srcfileName = desfolderdir + "\\" + srcfileName; if (!Directory.Exists(desfolderdir)) { Directory.CreateDirectory(desfolderdir); } File.Copy(file, srcfileName); } } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
不复制主文件夹
private void CopyDirectory(string srcdir, string desdir) { try { if (File.Exists(srcdir)) { File.Copy(srcdir, desdir); } else { string folderName = srcdir.Substring(srcdir.LastIndexOf("\\") + 1); string desfolderdir = desdir ; //string desfolderdir = desdir + "\\" + folderName; if (desdir.LastIndexOf("\\") == (desdir.Length - 1)) { desfolderdir = desdir + folderName; } string[] filenames = Directory.GetFileSystemEntries(srcdir); foreach (string file in filenames)// 遍历所有的文件和目录 { if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件 { string currentdir = desdir + "\\" + file.Substring(file.LastIndexOf("\\") + 1); if (!Directory.Exists(currentdir)) { Directory.CreateDirectory(currentdir); } desfolderdir = desdir + "\\" + file.Substring(file.LastIndexOf("\\") + 1); CopyDirectory(file, desfolderdir); } else // 否则直接copy文件 { string srcfileName = file.Substring(file.LastIndexOf("\\") + 1); srcfileName = desfolderdir + "\\" + srcfileName; if (!Directory.Exists(desfolderdir)) { Directory.CreateDirectory(desfolderdir); } File.Copy(file, srcfileName); } } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
时间: 2024-10-07 23:10:56