文本文件从磁盘读取、写入
来源:互联网 发布:linux入门教程视频 编辑:程序博客网 时间:2024/05/01 08:18
- using System;
- using System.Text;
- using System.IO;
-
- namespace XXXX.Common
- {
-
-
-
- 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();
- }
- }
-
-
-
-
-
-
- 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);
- }
- }
- }