一个FileManager
一个文件操作的集合,包含文件的读取,写入,判存,删除等。
using System.Collections.Generic;
using System.IO;
using System.Text;
public class FileManager
{
public static bool Exits(string path)
{
return File.Exists(path);
}
public static void Delete(string path)
{
File.Delete(path);
}
public static IEnumerable ReadLine(string path)
{
using (StreamReader reader = new StreamReader(path, Encoding.Default))
{
while (!reader.EndOfStream)
{
yield return reader.ReadLine();
}
reader.Close();
reader.Dispose();
}
}
public static string ReadFile(string path)
{
if (!Exits(path))
return null;
using (StreamReader reader = new StreamReader(path, Encoding.Default))
{
string content = reader.ReadToEnd();
reader.Close();
reader.Dispose();
return content;
}
}
public static void WriteLine(string path, string content, bool append = false)
{
CheckDirectory(path, true);
using (StreamWriter writer = new StreamWriter(path, append, Encoding.Default))
{
writer.WriteLine(content);
writer.Flush();
writer.Close();
writer.Dispose();
}
}
public static void WriteFile(string path, string content, bool append = false)
{
CheckDirectory(path, true);
using (StreamWriter writer = new StreamWriter(path, append, Encoding.Default))
{
writer.Write(content);
writer.Flush();
writer.Close();
writer.Dispose();
}
}
public static void SaveStream(string path, byte[] data)
{
CheckDirectory(path, true);
using (FileStream stream = new FileStream(path, FileMode.Create))
{
stream.Write(data, 0, data.Length);
stream.Flush();
stream.Close();
stream.Dispose();
}
}
public static byte[] ReadStream(string path)
{
if (!Exits(path))
return null;
using (FileStream stream = new FileStream(path, FileMode.Open))
{
byte[] data = new byte[stream.Length];
stream.Read(data, 0, (int)stream.Length);
stream.Close();
stream.Dispose();
return data;
}
}
public static bool CheckDirectory(string path, bool autoCreat = false)
{
int lastIndex = path.LastIndexOf('/');
lastIndex = lastIndex < 0 ? path.LastIndexOf('\\') : lastIndex;
path = path.Substring(0, lastIndex);
bool exits = Directory.Exists(path);
if (!exits && autoCreat)
{
DirectoryInfo dict = Directory.CreateDirectory(path);
}
return exits;
}
}
2017/7/16 修改 SaveStream方法的FileMode由OpenOrCreate改为Create
- 上一篇: 一个Util工具类
- 下一篇: 关于Http版的服务器推送?