C#查看文件目录操作、复制、替换
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 List<FileInfo> lst = new List<FileInfo>(); 6 string strPath = @"E:\aaa"; 7 List<FileInfo> lstFiles = getFile(strPath, ".aspx", lst); 8 foreach (FileInfo shpFile in lstFiles) 9 { 10 string aspxFile=""; 11 aspxFile += shpFile.FullName + "\n"; 12 DirectoryInfo di = new DirectoryInfo("E:/bbb"); 13 DirectoryInfo di2 = new DirectoryInfo("E:/ccc"); 14 CopyFilesRecursively(di,di2); //复制目录文件到新文件夹 15 //DeleteFolder("E:/syjd_bak/abc"); //删除文件目录 16 DeleteBaiDuShangQiaoJStream("E:/ccc/myfile.txt"); //替换目录文件夹内容 17 18 19 } 20 } 21 22 //删除文件目录 23 public static void DeleteFolder(string dir) 24 { 25 if (Directory.Exists(dir)) 26 { 27 foreach (string d in Directory.GetFileSystemEntries(dir)) 28 { 29 if (File.Exists(d)) 30 File.Delete(d); 31 else 32 DeleteFolder(d); 33 } 34 Directory.Delete(dir, true); 35 36 } 37 } 38 //复制文件到其它目录 39 private static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target) 40 { 41 foreach (DirectoryInfo dir in source.GetDirectories()) 42 { 43 CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name)); 44 } 45 46 foreach (FileInfo file in source.GetFiles()) 47 { 48 file.CopyTo(Path.Combine(target.FullName, file.Name), true); 49 } 50 } 51 //替换文件相关内容 52 private static void DeleteBaiDuShangQiaoJStream(string FilePath) 53 { 54 string _html = ""; 55 //打开文件流 56 FileStream file = new FileStream(FilePath, FileMode.Open, FileAccess.Read); 57 //获取输出流 58 StreamReader sr = new StreamReader(file); 59 //读取文件所有内容并转为字符串 60 _html = sr.ReadToEnd(); 61 //释放资源 62 sr.Dispose(); 63 file.Dispose(); 64 //通过正则匹配,删除百度商桥的相关JS文件 65 _html = _html.Replace(@"Windows 7", @"Windows 2007"); 66 //覆盖文件流 67 file = new FileStream(FilePath, FileMode.Truncate, FileAccess.Write); 68 //获取输入流 69 StreamWriter sw = new StreamWriter(file); 70 //覆盖 71 sw.WriteLine(_html); 72 //释放资源 73 sw.Dispose(); 74 file.Dispose(); 75 } 76 //显示当前目录下的所有文件 77 public static List<FileInfo> getFile(string path, string extName, List<FileInfo> lst) 78 { 79 try 80 { 81 82 string[] dir = Directory.GetDirectories(path); //文件夹列表 83 DirectoryInfo fdir = new DirectoryInfo(path); 84 FileInfo[] file = fdir.GetFiles(); 85 //FileInfo[] file = Directory.GetFiles(path); //文件列表 86 if (file.Length != 0 || dir.Length != 0) //当前目录文件或文件夹不为空 87 { 88 foreach (FileInfo f in file) //显示当前目录所有文件 89 { 90 if (extName.ToLower().IndexOf(f.Extension.ToLower()) >= 0) 91 { 92 lst.Add(f); 93 } 94 } 95 foreach (string d in dir) 96 { 97 getFile(d, extName, lst);//递归 98 } 99 } 100 return lst; 101 } 102 catch (Exception ex) 103 { 104 throw ex; 105 } 106 } 107 }
好的代码就和美食一样,都是需要时间烹饪出来的!