標籤:
複製主資料夾
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()); } }
c#複製檔案夾(複製主資料夾和不複製主資料夾)