標籤:foreach title cat director exce dir 建立 create static
public static void CopyDirectory(string srcPath, string destPath){ try {
DirectoryInfo dir = new DirectoryInfo(srcPath);
FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //擷取目錄下(不包含子目錄)的檔案和子目錄 foreach (FileSystemInfo i in fileinfo) { if (i is DirectoryInfo) //判斷是否檔案夾 { if (!Directory.Exists(destPath+"\\"+i.Name)) { Directory.CreateDirectory(destPath + "\\" + i.Name); //目標目錄下不存在此檔案夾即建立子檔案夾 } CopyDir(i.FullName, destPath + "\\" + i.Name); //遞迴調用複製子檔案夾 } else { File.Copy(i.FullName, destPath + "\\" + i.Name,true); //不是檔案夾即複製檔案,true表示可以覆蓋同名檔案 } } } catch (Exception e) { throw; }
}
調用CopyDirectory方法前可以先判斷原路徑與目標路徑是否存在
if(Directory.Exists(srcPath)&&Directory.Exists(destPath)){ CopyDirectory(srcPath,destPath);
}
原文地址:http://www.cnblogs.com/iamlucky/p/5996222.html
C# 把一個檔案夾下所有檔案刪除
public static void DelectDir(string srcPath)
{ try { DirectoryInfo dir = new DirectoryInfo(srcPath); FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //返回目錄中所有檔案和子目錄 foreach (FileSystemInfo i in fileinfo) { if (i is DirectoryInfo) //判斷是否檔案夾 { DirectoryInfo subdir = new DirectoryInfo(i.FullName); subdir.Delete(true); //刪除子目錄和檔案 } else { File.Delete(i.FullName); //刪除指定檔案 } } } catch (Exception e) { throw; }
}
調用DelectDir方法前可以先判斷檔案夾是否存在
if(Directory.Exists(srcPath)){ DelectDir(srcPath);}
原文地址:http://www.cnblogs.com/iamlucky/p/5997865.html
C# 把一個檔案夾下所有檔案複製到另一個檔案夾下 把一個檔案夾下所有檔案刪除(轉)