檔案移動(Move)操作和檔案的復制(Copy)是C#程式開發經常遇到的方法,根據傳入的源檔案地址和目標檔案地址引數,實作對檔案的操作,實作代碼如下:
- Move操作代碼:
public static void MoveFolder(string sourcePath, string destPath) { if (Directory.Exists(sourcePath)) { if (!Directory.Exists(destPath)) { //目標目錄不存在則創建 try { Directory.CreateDirectory(destPath); } catch (Exception ex) { throw new Exception("創建目標目錄失敗:" + ex.Message); } } //獲得源檔案下所有檔案 List<string> files = new List<string>(Directory.GetFiles(sourcePath)); files.ForEach(c => { string destFile = Path.Combine(new string[] { destPath, Path.GetFileName(c) }); //覆寫模式 if (File.Exists(destFile)) { File.Delete(destFile); } File.Move(c, destFile); }); //獲得源檔案下所有目錄檔案 List<string> folders = new List<string>(Directory.GetDirectories(sourcePath)); folders.ForEach(c => { string destDir = Path.Combine(new string[] { destPath, Path.GetFileName(c) }); //Directory.Move必須要在同一個根目錄下移動才有效,不能在不同卷中移動, //Directory.Move(c, destDir); //采用遞回的方法實作 MoveFolder(c, destDir); }); } else {
Move - Copy操作代碼:
public static void CopyFilefolder(string sourceFilePath, string targetFilePath) { //獲取源檔案夾中的所有非目錄檔案 string[] files = Directory.GetFiles(sourceFilePath); string fileName; string destFile; //如果目標檔案夾不存在,則新建目標檔案夾 if (!Directory.Exists(targetFilePath)) { Directory.CreateDirectory(targetFilePath); } //將獲取到的檔案一個一個拷貝到目標檔案夾中 foreach (string s in files) { fileName = Path.GetFileName(s); destFile = Path.Combine(targetFilePath, fileName); File.Copy(s, destFile, true); } //上面一段在MSDN上可以看到原始碼 //獲取并存盤源檔案夾中的檔案夾名 string[] filefolders = Directory.GetFiles(sourceFilePath); //創建Directoryinfo實體 DirectoryInfo dirinfo = new DirectoryInfo(sourceFilePath); //獲取得源檔案夾下的所有子檔案夾名 DirectoryInfo[] subFileFolder = dirinfo.GetDirectories(); for (int j = 0; j < subFileFolder.Length; j++) { //獲取所有子檔案夾名 string subSourcePath = sourceFilePath + "\\" + subFileFolder[j].ToString(); string subTargetPath = targetFilePath + "\\" + subFileFolder[j].ToString(); //把得到的子檔案夾當成新的源檔案夾,遞回呼叫CopyFilefolder CopyFilefolder(subSourcePath, subTargetPath); } }
Copy
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/82976.html
標籤:C#
