////// 文本文件从磁盘读取、写入 /// public class FileHelper { ////// 从文件中读取文本内容 /// /// 文本路径 ///返回文件中的内容 public static string Read(string filePath) { string result = string.Empty; if (File.Exists(filePath)) { using (StreamReader sr = new StreamReader(filePath, Encoding.Default)) { result = sr.ReadToEnd(); sr.Close(); return result; } } return result; } ////// 写入文本文件,按默认编码 /// /// 文本文件路径包括文件名 /// 写入内容 public static void Write(string filePath, string content) { using (StreamWriter sw = new StreamWriter(filePath, false, Encoding.Default)) { sw.Write(content); sw.Close(); } } ////// 写入文本文件,以UFT8格式编码 /// /// 文本文件路径包括文件名 /// 写入内容 /// public static void Write(string filePath, string content, bool UTF8) { using (StreamWriter sw = new StreamWriter(filePath, false, Encoding.UTF8)) { sw.Write(content); sw.Close(); } } ////// 备份文件 /// /// 源文件路径 /// 目标文件路径 /// 是否覆盖已存在文件 ///public static bool BackupFile(string sourceFileName, string destFileName, bool overwrite) { bool flag; if (!File.Exists(sourceFileName)) { throw new FileNotFoundException(sourceFileName + "文件不存在!"); } if (!overwrite && File.Exists(destFileName)) { return false; } try { File.Copy(sourceFileName, destFileName, true); flag = true; } catch (Exception exception) { throw exception; } return flag; } /// /// 拷贝文件夹文件 /// /// /// public static void CopyDirFiles(string srcDir, string dstDir) { if (Directory.Exists(srcDir)) { foreach (string str in Directory.GetFiles(srcDir)) { string destFileName = Path.Combine(dstDir, Path.GetFileName(str)); File.Copy(str, destFileName, true); } foreach (string str3 in Directory.GetDirectories(srcDir)) { string str4 = str3.Substring(str3.LastIndexOf(@"\") + 1); CopyDirFiles(Path.Combine(srcDir, str4), Path.Combine(dstDir, str4)); } } } ////// 删除文件夹文件 /// /// public static void DeleteDirFiles(string dir) { if (Directory.Exists(dir)) { foreach (string str in Directory.GetFiles(dir)) { File.Delete(str); } foreach (string str2 in Directory.GetDirectories(dir)) { Directory.Delete(str2, true); } } } ////// 获得文件最后修改时间 /// /// ///public static DateTime GetFileLastWriteTime(string file) { if (File.Exists(file)) { return File.GetLastWriteTime(file); } return DateTime.MaxValue; } /// /// 取消文件的只读属性 /// /// public static void RemoveFileReadOnlyAttribute(string file) { File.SetAttributes(file, File.GetAttributes(file) & ~FileAttributes.ReadOnly); } }