如何復制一個目錄里面的所有目錄和文件
2024-07-21 02:16:19
供稿:網友
 
本文介紹如何將一個目錄里面的所有文件復制到目標目錄里面。
下面介紹幾個我們在該例程中將要使用的類:
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帳號足夠的權限,不過這樣做是很危險的,不建議這樣做。