MSDN的File类
File类在MSDN:https://msdn.microsoft.com/zh-cn/library/system.io.file_methods(v=vs.110).aspx
FileHelper.cs
FileHelper提供的功能:
- 递归获取指定目录下所有的文件
- 获取指定目录下所有的子目录
using System; using System.Collections.Generic; using System.IO; public class FileHelper { /// <summary> /// 递归获取所有的目录 /// </summary> /// <param name="strPath"></param> /// <param name="lstDirect"></param> public static void GetAllDirectorys(string strPath, ref List<string> lstDirect) { if (Directory.Exists(strPath) == false) { Console.WriteLine("请检查,路径不存在:{0}",strPath); return; } DirectoryInfo diFliles = new DirectoryInfo(strPath); DirectoryInfo[] directories = diFliles.GetDirectories(); var max = directories.Length; for (int dirIdx = 0; dirIdx < max; dirIdx++) { try { var dir = directories[dirIdx]; //dir.FullName是某个子目录的绝对地址,把它记录起来 lstDirect.Add(dir.FullName); GetAllDirectorys(dir.FullName, ref lstDirect); } catch { continue; } } } /// <summary> /// 遍历当前目录及子目录,获取所有文件 /// </summary> /// <param name="strPath">文件路径</param> /// <returns>所有文件</returns> public static IList<FileInfo> GetAllFiles(string strPath) { List<FileInfo> lstFiles = new List<FileInfo>(); List<string> lstDirect = new List<string>(); lstDirect.Add(strPath); DirectoryInfo diFliles = null; GetAllDirectorys(strPath, ref lstDirect); var max = lstDirect.Count; for (int idx = 0; idx < max; idx++) { try { diFliles = new DirectoryInfo(lstDirect[idx]); lstFiles.AddRange(diFliles.GetFiles()); } catch { continue; } } return lstFiles; } }
File类实用方法
获取父目录
var currentDirectory = System.Environment.CurrentDirectory;//当前程序的目录 var parentDirPath = string.Empty; var parentDir = new DirectoryInfo(currentDirectory).Parent; if (parentDir != null) { parentDirPath = parentDir.FullName; //上一级目录 } else { Console.WriteLine("ERROR:当前目录没有父级目录"); }
读取和修改文本内容
//读取所有内容 var fileContent = File.ReadAllText(versionFileName); //修改文本内容 File.WriteAllText(versionFileName, strNewVer);
方法二
参考文档:https://msdn.microsoft.com/zh-cn/library/8bh11f1k.aspx
using (var sw = new StreamWriter(FilePath)) { sw.Write(sb.ToString()); }
创建文本并写入内容
using (StreamWriter streamWriter = File.CreateText(resFileName)) { var fileInfos = FileHelper.GetAllFiles(targetPath); var fileMax = fileInfos.Count; for (int fileIdx = 0; fileIdx < fileMax; fileIdx++) { var fileInfo = fileInfos[fileIdx]; if (fileInfo.Extension != ".meta") { var filePath = fileInfo.FullName.Replace(parentDirPath, ""); filePath = filePath.Replace(@"", "/"); var fileStr = string.Concat(filePath, "&", HashHelper.GetSHA1(fileInfo.FullName)); streamWriter.WriteLine(fileStr); Console.WriteLine(fileStr); if (fileLine < Int64.MaxValue) { fileLine += 1; } else { overflowMsg = "文件行数太多啦,未统计。"; } } } }
@ 文件路径
var filePath = @"d:Tools"; 等价于 var filePath = "d:\Tools\";