using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace BackupAndImport { class Tools { /// /// 获取指定目录中的匹配文件 /// /// 要搜索的目录 /// 文件名模式(正则)。null表示忽略模式匹配,返回所有文件 /// 递归深度。负数表示不限,0表示仅顶级 /// 是否抛异常 /// GetFiles(path,"(?(数据库.db)|(aliTools.db))",-1) public static string[] GetFiles(string dir, string regexPattern = null, int depth = 0, bool throwEx = false) { List lst = new List(); try { foreach (string item in Directory.GetFileSystemEntries(dir)) { try { bool isFile = (File.GetAttributes(item) & FileAttributes.Directory) != FileAttributes.Directory; if (isFile && (regexPattern == null || Regex.IsMatch(Path.GetFileName(item), regexPattern, RegexOptions.IgnoreCase | RegexOptions.Multiline))) { lst.Add(item); } //递归 if (depth != 0 && !isFile) { lst.AddRange(GetFiles(item, regexPattern, depth - 1, throwEx)); } } catch { if (throwEx) { throw; } } } } catch { if (throwEx) { throw; } } return lst.ToArray(); } /// /// 序列化 对象到字符串 /// /// 泛型对象 /// 序列化后的字符串 public static string Serialize(T obj) { try { IFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); formatter.Serialize(stream, obj); stream.Position = 0; byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); stream.Flush(); stream.Close(); return Convert.ToBase64String(buffer); } catch (Exception ex) { throw new Exception("序列化失败,原因:" + ex.Message); } } /// /// 反序列化 字符串到对象 /// /// 泛型对象 /// 要转换为对象的字符串 /// 反序列化出来的对象 public static T Desrialize(T obj, string str) { try { obj = default(T); IFormatter formatter = new BinaryFormatter(); byte[] buffer = Convert.FromBase64String(str); MemoryStream stream = new MemoryStream(buffer); obj = (T)formatter.Deserialize(stream); stream.Flush(); stream.Close(); } catch (Exception ex) { throw new Exception("反序列化失败,原因:" + ex.Message); } return obj; } } }