程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> c#如何復制一個目錄裡面的所有目錄和文件

c#如何復制一個目錄裡面的所有目錄和文件

編輯:關於C#
 

本文介紹如何將一個目錄裡面的所有文件復制到目標目錄裡面。
下面介紹幾個我們在該例程中將要使用的類:
1、Directory:Exposes static methods for creating, moving, and enumerating through directories and subdirectories.
2、Path:Performs operations on String instances that contain file or directory path information. These operations are performed in a cross-platform manner.
3、File:Provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.
這兩個類裡都是不可繼承的,是從object直接繼承來的,被實現成sealed,上面的解釋均來自MSDN。
下面是實現的代碼,代碼中的細節不在這裡詳細描述,請看代碼注釋:
// ======================================================
// 實現一個靜態方法將指定文件夾下面的所有內容copy到目標文件夾下面
// ======================================================
public static void CopyDir(string srcPath,string aimPath){
// 檢查目標目錄是否以目錄分割字符結束如果不是則添加之
if(aimPath[aimPath.Length-1] != Path.DirectorySeparatorChar)
aimPath += Path.DirectorySeparatorChar;
// 判斷目標目錄是否存在如果不存在則新建之
if(!Directory.Exists(aimPath)) Directory.CreateDirectory(aimPath);
// 得到源目錄的文件列表,該裡面是包含文件以及目錄路徑的一個數組
// 如果你指向copy目標文件下面的文件而不包含目錄請使用下面的方法
// string[] fileList = Directory.GetFiles(srcPath);
string[] fileList = Directory.GetFileSystemEntries(srcPath);
// 遍歷所有的文件和目錄
foreach(string file in fileList){
// 先當作目錄處理如果存在這個目錄就遞歸Copy該目錄下面的文件
if(Directory.Exists(file))
CopyDir(file,aimPath+Path.GetFileName(file));
// 否則直接Copy文件
else
File.Copy(file,aimPath+Path.GetFileName(file),true);
}
}
嘿嘿!這次給大家說的功能比較簡單,適合初學者,希望對初學者有所幫助!如果你需要將該功能使用在Web工程中,那麼請設置給ASPNET帳號足夠的權限,不過這樣做是很危險的,不建議這樣做。
 

 
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved