using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.IO;
|
|
|
|
namespace Utils.Files
|
|
{
|
|
public class ReadWriteFile
|
|
{
|
|
/// <summary>
|
|
/// 读取指定文件(路径与文件名)的内容
|
|
/// <para>文件不存在时,返回string.Empty</para>
|
|
/// </summary>
|
|
/// <param name="path">路径与文件名</param>
|
|
/// <returns>文件的内容</returns>
|
|
public static string ReadFile(string path)
|
|
{
|
|
var fileStrings = string.Empty;
|
|
|
|
try {
|
|
FileStream fs = new FileStream(path, FileMode.Open);
|
|
StreamReader sr = new StreamReader(fs, Encoding.Default);
|
|
while (true) {
|
|
if (sr.EndOfStream)
|
|
break;
|
|
fileStrings = sr.ReadToEnd();
|
|
}
|
|
sr.Close();
|
|
fs.Close();
|
|
} catch (FileNotFoundException) {
|
|
}
|
|
|
|
return fileStrings;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 重写指定文件的数据
|
|
/// <para>如果文件不存在则创建一个新的文件。路径必须存在。</para>
|
|
/// </summary>
|
|
/// <param name="path">路径与文件名</param>
|
|
/// <param name="content">文件内容</param>
|
|
public static void WriteFile(string path, string content)
|
|
{
|
|
FileStream fs = new FileStream(path, FileMode.Create);
|
|
StreamWriter sw = new StreamWriter(fs);
|
|
//开始写入
|
|
sw.Write(content);
|
|
//清空缓冲区
|
|
sw.Flush();
|
|
//关闭流
|
|
sw.Close();
|
|
fs.Close();
|
|
}
|
|
|
|
}
|
|
}
|