下面一段代碼給大家介紹C#拷貝整個文件夾以及子目錄和其中文件,具體代碼如下所示:
private void CopyDirectory( string srcPath, string desPath) { string folderName = srcdir.Substring(srcdir.LastIndexOf( "http://" )+1); string desfolderdir = desPath + "http://" + folderName; if (desdir.LastIndexOf( "http://" ) == (desPath.Length - 1)) { desfolderdir = desPath + folderName; } string [] filenames = Directory.GetFileSystemEntries(srcPath); foreach ( string file in filenames) { if (Directory.Exists(file)) { string currentdir = desfolderdir + "http://" + file.Substring(file.LastIndexOf( "http://" ) + 1); if (!Directory.Exists(currentdir)) { Directory.CreateDirectory(currentdir); } CopyDirectory(file, desfolderdir); } else { string srcfileName = file.Substring(file.LastIndexOf( "http://" )+1); srcfileName = desfolderdir + "http://" + srcfileName; if (!Directory.Exists(desfolderdir)) { Directory.CreateDirectory(desfolderdir); } File.Copy(file, srcfileName); } } }ps:C# 拷貝指定文件夾下的所有文件及其文件夾到指定目錄
要拷貝的文件及其文件夾結構

其中.lab文件不能覆蓋
/// <summary>/// 拷貝oldlab的文件到newlab下面/// </summary>/// <param name="sourcePath">lab文件所在目錄(@"~/labs/oldlab")</param>/// <param name="savePath">保存的目標目錄(@"~/labs/newlab")</param>/// <returns>返回:true-拷貝成功;false:拷貝失敗</returns>public bool CopyOldLabFilesToNewLab(string sourcePath, string savePath){ if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } #region //拷貝labs文件夾到savePath下 try { string[] labDirs = Directory.GetDirectories(sourcePath);//目錄 string[] labFiles = Directory.GetFiles(sourcePath);//文件 if (labFiles.Length > 0) { for (int i = 0; i < labFiles.Length; i++) { if (Path.GetExtension(labFiles[i]) != ".lab")//排除.lab文件 { File.Copy(sourcePath + "http://" + Path.GetFileName(labFiles[i]), savePath + "http://" + Path.GetFileName(labFiles[i]), true); } } } if (labDirs.Length > 0) { for (int j = 0; j < labDirs.Length; j++) { Directory.GetDirectories(sourcePath + "http://" + Path.GetFileName(labDirs[j])); //遞歸調用 CopyOldLabFilesToNewLab(sourcePath + "http://" + Path.GetFileName(labDirs[j]), savePath + "http://" + Path.GetFileName(labDirs[j])); } } } catch (Exception) { return false; } #endregion return true;}新聞熱點
疑難解答