1. 程式人生 > >C# 把一個文件夾下所有文件復制到另一個文件夾下 把一個文件夾下所有文件刪除(轉)

C# 把一個文件夾下所有文件復制到另一個文件夾下 把一個文件夾下所有文件刪除(轉)

body 圖片 rec UC class lB delet gif OS

技術分享圖片
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# 把一個文件夾下所有文件復制到另一個文件夾下 把一個文件夾下所有文件刪除(轉)