1.判断目录或文件是否存在(using System.IO;):
Directory.Exists(path);//目录是否存在
File.Exists(filePath);//文件是否存在
2.创建路径上所有目录及子目录:
Directory.CreateDirectory(path);
3.获取目录下所有子目录:
string[] dirs = Directory.GetDirectories(dirPath);
4.获取目录下所有文件或指定后缀文件:
string[] files = Directory.GetFiles(path); string[] files = Directory.GetFiles(path,"*.txt");
5.使用遍历获取目录下所有文件:
1 void GetAllFiles(string root) 2 { 3 string[] dirs = Directory.GetDirectories(root); 4 string[] files = Directory.GetFiles(root); 5 foreach (string f in files) 6 { 7 FileInfo file = new FileInfo(f); 8 Console.WriteLine(f + " " + file.CreationTime + " " + file.Length + "B"); 9 } 10 foreach (string d in dirs) 11 GetAllFiles(d); 12 }
6.使用遍历由内而外删除目录下所有文件及目录:
1 void DeleteAllFiles(string root) 2 { 3 DirectoryInfo folder = new DirectoryInfo(root); 4 FileInfo[] files = folder.GetFiles(); 5 DirectoryInfo[] childFolders = folder.GetDirectories(); 6 foreach (DirectoryInfo chldFolder in childFolders) 7 DeleteAllFiles(chldFolder.FullName); 8 foreach (DirectoryInfo chldFolder in childFolders) 9 { 10 chldFolder.Delete(); 11 Console.WriteLine("Delete Folder:" + chldFolder.FullName); 12 } 13 foreach (FileInfo f in files) 14 { 15 f.Delete(); 16 Console.WriteLine("Delete Files:" + f.FullName); 17 } 18 }
7.将数据写入到文件,若不存在则创建文件:
1 using (FileStream fs = new FileStream(path + file, FileMode.Append, FileAccess.Write)) 2 { 3 using (StreamWriter sw = new StreamWriter(fs)) 4 { 5 sw.WriteLine("123"); 6 sw.Flush(); 7 sw.Close(); 8 File.Copy(path + file, path + copy, true); 9 } 10 fs.Close(); 11 }
8.读取文件数据:
1 using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) 2 { 3 using (StreamReader sr = new StreamReader(fs)) 4 { 5 while (true) 6 { 7 string line = sr.ReadLine(); 8 if (line == null) 9 break; 10 Console.WriteLine(f + ":" + line); 11 } 12 sr.Close(); 13 } 14 fs.Close(); 15 }
9.压缩目录文件夹(using System.IO.Compression):
ZipFile.CreateFromDirectory(oldPath, zipPath, CompressionLevel.Optimal, true);
10.解压压缩包:
ZipFile.ExtractToDirectory(zipPath, "D:\\test");
11.向压缩包追加文件:
using (FileStream fs = new FileStream(zipPath, FileMode.Open)) { using (ZipArchive arch = new ZipArchive(fs, ZipArchiveMode.Update)) arch.CreateEntryFromFile(file, Path.GetFileName(file)); }
标签:fs,函数,C#,压缩文件,file,new,Directory,using,string From: https://www.cnblogs.com/cfsl/p/17046822.html