using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using XFEExtension.TaskExtension;
namespace XFEExtension.FileExtension
{
///
/// 文件的拓展
///
public static class FileExtension
{
///
/// 将字符串写入文件
///
///
/// 目标文件路径及文件名
public static void WriteIn(this string txt, string fileName)
{
FileInfo rd = new FileInfo(fileName);
using (FileStream fs = rd.Create())
{
var stream = Encoding.UTF8.GetBytes(txt);
fs.Write(stream, 0, stream.Length);
fs.Flush();
}
}
///
/// 将非法字符串写入文件
///
///
/// 文件名
public static void WriteInObj(this object bin, string fileName)
{
FileInfo rd = new FileInfo(fileName);
using (FileStream fs = rd.Create())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, bin);
fs.Flush();
fs.Close();
}
}
///
/// 读取文件中的字符串
///
///
/// 读取的内容
/// 被读取的文件是否存在
public static bool ReadOut(this string Name, out string Content)
{
FileInfo rd = new FileInfo(Name);
if (rd.Exists)
{
using (StreamReader sr = rd.OpenText())
{
Content = sr.ReadLine();
sr.Close();
return true;
}
}
else
{
Content = string.Empty;
return false;
}
}
///
/// 读取文件中的字符串
///
/// 目标文件路径及文件名
/// 目标文件内容,如不存在则返回-1
public static string ReadOut(this string fileName)
{
FileInfo rd = new FileInfo(fileName);
if (rd.Exists)
{
using (StreamReader sr = rd.OpenText())
{
string text = sr.ReadLine();
sr.Close();
return text;
}
}
else
{
return "-1";
}
}
///
/// 读取文件中的字符串
///
///
///
public static T ReadOutObj(this string fileName)
{
FileInfo rd = new FileInfo(fileName);
if (rd.Exists)
{
using (FileStream fs = rd.OpenRead())
{
BinaryFormatter bf = new BinaryFormatter();
var result = (T)bf.Deserialize(fs);
fs.Close();
return result;
}
}
else
{
return default(T);
}
}
///
/// 读取文件中的字符串
///
/// 目标文件路径及文件名
/// 目标文件是否存在
/// 目标文件内容,如不存在则返回-1
public static string ReadOut(string fileName, out bool exist)
{
FileInfo rd = new FileInfo(fileName);
exist = rd.Exists;
if (rd.Exists)
{
using (StreamReader sr = rd.OpenText())
{
string text = sr.ReadLine();
sr.Close();
return text;
}
}
else
{
return "-1";
}
}
///
/// 读取文件中的字符串
///
///
/// 是否存在
///
public static string ReadOutObj(this string fileName, out bool exist)
{
FileInfo rd = new FileInfo(fileName);
exist = rd.Exists;
if (rd.Exists)
{
using (FileStream fs = rd.OpenRead())
{
BinaryFormatter bf = new BinaryFormatter();
string bin = bf.Deserialize(fs).ToString();
fs.Close();
return bin;
}
}
else
{
return "-1";
}
}
///
/// 序列化对象到文件
///
///
/// 文件路径
public static void SerializeToFile(this object obj, string fileName)
{
BinaryFormatter WriteBinary = new BinaryFormatter();
using (var WriteStream = File.OpenWrite(fileName))
{
WriteBinary.Serialize(WriteStream, obj);
WriteStream.Flush();
WriteStream.Close();
}
}
///
/// 从文件反序列化对象
///
/// 类型
///
///
public static T DeserializeFromFile(this string fileName)
{
BinaryFormatter ReadBinary = new BinaryFormatter();
using (var ReadStream = File.OpenRead(fileName))
{
T obj = (T)ReadBinary.Deserialize(ReadStream);
ReadStream.Close();
return obj;
}
}
///
/// 输出文件大小
///
///
///
public static string FileSize(this long bufferLength)
{
string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = bufferLength;
int order = 0;
while (len >= 1024 && order < sizes.Length - 1)
{
order++;
len /= 1024;
}
return String.Format("{0:0.##} {1}", len, sizes[order]);
}
}
///
/// XFE文件监视器
///
public class XFEFileWatcher
{
#region 字段
private List watchers = new List();
#endregion
#region 属性
///
/// 是否遍历监视所有子文件夹
///
public bool WatchSubdirectories { get; set; }
///
/// 文件或文件夹路径
///
public string Path { get; set; }
#endregion
#region 事件
///
/// 文件发生改变时触发
///
public event FileSystemEventHandler FileChanged;
///
/// 文件被创建时触发
///
public event FileSystemEventHandler FileCreated;
///
/// 文件被删除时触发
///
public event FileSystemEventHandler FileDeleted;
///
/// 文件被重命名时触发
///
public event RenamedEventHandler FileRenamed;
#endregion
#region 方法
private void OnFileChanged(object sender, FileSystemEventArgs e)
{
switch (e.ChangeType)
{
case WatcherChangeTypes.Changed:
FileChanged?.Invoke(sender, e);
break;
case WatcherChangeTypes.Created:
FileCreated?.Invoke(sender, e);
break;
case WatcherChangeTypes.Deleted:
FileDeleted?.Invoke(sender, e);
break;
default:
break;
}
}
private void OnFileRenamed(object sender, RenamedEventArgs e)
{
FileRenamed?.Invoke(sender, e);
}
private void MonitorSubdirectories(string folderPath)
{
string[] subdirectories = Directory.GetDirectories(folderPath);
foreach (string subdirectory in subdirectories)
{
try
{
FileSystemWatcher subdirectoryWatcher = new FileSystemWatcher(subdirectory);
subdirectoryWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
watchers.Add(subdirectoryWatcher);
subdirectoryWatcher.Changed += OnFileChanged;
subdirectoryWatcher.Created += OnFileChanged;
subdirectoryWatcher.Deleted += OnFileChanged;
subdirectoryWatcher.Renamed += OnFileRenamed;
subdirectoryWatcher.EnableRaisingEvents = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
continue;
}
MonitorSubdirectories(subdirectory);
}
}
///
/// 启动监视
///
///
///
public async Task StartWatchingAsync()
{
if (Path != null && Path != string.Empty)
{
if (File.Exists(Path) || Directory.Exists(Path))
{
if (WatchSubdirectories && Directory.Exists(Path))
{
await new Action(() => { MonitorSubdirectories(Path); }).StartNewTask();
}
FileSystemWatcher rootWatcher = new FileSystemWatcher(Path);
watchers.Add(rootWatcher);
rootWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
rootWatcher.Changed += OnFileChanged;
rootWatcher.Created += OnFileChanged;
rootWatcher.Deleted += OnFileChanged;
rootWatcher.Renamed += OnFileRenamed;
}
else
{
throw new XFEExtensionException("文件或文件夹不存在");
}
}
else
{
throw new XFEExtensionException("未设置属性");
}
}
///
/// 启动监视
///
///
///
public void StartWatching()
{
if (Path != null && Path != string.Empty)
{
if (File.Exists(Path) || Directory.Exists(Path))
{
if (WatchSubdirectories && Directory.Exists(Path))
{
MonitorSubdirectories(Path);
}
FileSystemWatcher rootWatcher = new FileSystemWatcher(Path);
watchers.Add(rootWatcher);
rootWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
rootWatcher.Changed += OnFileChanged;
rootWatcher.Created += OnFileChanged;
rootWatcher.Deleted += OnFileChanged;
rootWatcher.Renamed += OnFileRenamed;
}
else
{
throw new XFEExtensionException("文件或文件夹不存在");
}
}
else
{
throw new XFEExtensionException("未设置属性");
}
}
///
/// 停止监视
///
public void StopWatching()
{
foreach (FileSystemWatcher watcher in watchers)
{
watcher.EnableRaisingEvents = false;
}
}
///
/// 继续监视
///
public void ContinueWatching()
{
foreach (FileSystemWatcher watcher in watchers)
{
watcher.EnableRaisingEvents = true;
}
}
///
/// 释放资源
///
public void Dispose()
{
foreach (FileSystemWatcher watcher in watchers)
{
watcher.Dispose();
}
}
#endregion
#region 构造函数
///
/// XFE文件监视器
///
public XFEFileWatcher() { }
///
/// XFE文件监视器
///
/// 路径
/// 是否遍历监视所有子文件/文件夹
public XFEFileWatcher(string path, bool watchSubdirectories = false)
{
Path = path;
WatchSubdirectories = watchSubdirectories;
}
#endregion
}
}