using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Web; using System.Security.Cryptography; using MyCode.Project.Infrastructure; using MyCode.Project.Infrastructure.Common; [Serializable] public class FileItem { public FileItem() { } #region 私有字段 private string _Name; private string _FullName; private DateTime _CreationDate; private bool _IsFolder; private long _Size; private DateTime _LastAccessDate; private DateTime _LastWriteDate; private int _FileCount; private int _SubFolderCount; #endregion #region 公有属性 /// /// 名称 /// public string Name { get { return _Name; } set { _Name = value; } } /// /// 文件或目录的完整目录 /// public string FullName { get { return _FullName; } set { _FullName = value; } } /// /// 创建时间 /// public DateTime CreationDate { get { return _CreationDate; } set { _CreationDate = value; } } public bool IsFolder { get { return _IsFolder; } set { _IsFolder = value; } } /// /// 文件大小 /// public long Size { get { return _Size; } set { _Size = value; } } /// /// 上次访问时间 /// public DateTime LastAccessDate { get { return _LastAccessDate; } set { _LastAccessDate = value; } } /// /// 上次读写时间 /// public DateTime LastWriteDate { get { return _LastWriteDate; } set { _LastWriteDate = value; } } /// /// 文件个数 /// public int FileCount { get { return _FileCount; } set { _FileCount = value; } } /// /// 目录个数 /// public int SubFolderCount { get { return _SubFolderCount; } set { _SubFolderCount = value; } } #endregion } public class FileUtils { #region 构造函数 private static string strRootFolder; static FileUtils() { // strRootFolder = HttpContext.Current.Request.PhysicalApplicationPath + "File\\"; // strRootFolder = strRootFolder.Substring(0, strRootFolder.LastIndexOf(@"\")); strRootFolder = GetPhysicalPath("/File"); } #endregion #region 目录 /// /// 读根目录 /// public static string GetRootPath() { return strRootFolder; } /// /// 写根目录 /// public static void SetRootPath(string path) { strRootFolder = path; } /// /// 读取目录列表 /// public static List GetDirectoryItems() { return GetDirectoryItems(strRootFolder); } /// /// 读取目录列表 /// public static List GetDirectoryItems(string path) { List list = new List(); string[] folders = Directory.GetDirectories(path); foreach (string s in folders) { FileItem item = new FileItem(); DirectoryInfo di = new DirectoryInfo(s); item.Name = di.Name; item.FullName = di.FullName; item.CreationDate = di.CreationTime; item.IsFolder = false; list.Add(item); } return list; } #endregion #region 文件 /// /// 读取文件列表 /// public static List GetFileItems() { return GetFileItems(strRootFolder); } /// /// 读取文件列表 /// public static List GetFileItems(string path) { List list = new List(); string[] files = Directory.GetFiles(path); foreach (string s in files) { FileItem item = new FileItem(); FileInfo fi = new FileInfo(s); item.Name = fi.Name; item.FullName = fi.FullName; item.CreationDate = fi.CreationTime; item.IsFolder = true; item.Size = fi.Length; list.Add(item); } return list; } /// /// 创建文件 /// /// 全路径 /// public static bool CreateFile(string fullName) { try { FileStream fs = File.Create(fullName); fs.Close(); return true; } catch { return false; } } /// /// 创建文件 /// public static void CreateFile( string path,string content) { FileInfo file = new FileInfo(path); using (FileStream stream = file.Create()) { using (StreamWriter writer = new StreamWriter(stream, System.Text.Encoding.UTF8)) { writer.Write(content); writer.Flush(); } } } /// /// 读取文件 /// public static string OpenText(string parentName) { StreamReader sr = File.OpenText(parentName); StringBuilder output = new StringBuilder(); string rl; while ((rl = sr.ReadLine()) != null) { output.Append(rl); } sr.Close(); return output.ToString(); } /// /// 读取文件信息 /// public static FileItem GetItemInfo(string path) { FileItem item = new FileItem(); if (Directory.Exists(path)) { DirectoryInfo di = new DirectoryInfo(path); item.Name = di.Name; item.FullName = di.FullName; item.CreationDate = di.CreationTime; item.IsFolder = true; item.LastAccessDate = di.LastAccessTime; item.LastWriteDate = di.LastWriteTime; item.FileCount = di.GetFiles().Length; item.SubFolderCount = di.GetDirectories().Length; } else { FileInfo fi = new FileInfo(path); item.Name = fi.Name; item.FullName = fi.FullName; item.CreationDate = fi.CreationTime; item.LastAccessDate = fi.LastAccessTime; item.LastWriteDate = fi.LastWriteTime; item.IsFolder = false; item.Size = fi.Length; } return item; } /// /// 写入一个新文件,在文件中写入内容,然后关闭文件。如果目标文件已存在,则改写该文件。 /// public static bool WriteAllText(string parentName, string contents) { File.WriteAllText(parentName, contents, Encoding.UTF8); return true; } /// /// 删除文件 /// public static bool DeleteFile(string path) { try { File.Delete(path); return true; } catch { return false; } } /// /// 移动文件 /// public static bool MoveFile(string oldPath, string newPath) { try { File.Move(oldPath, newPath); return true; } catch { return false; } } #endregion #region 文件夹 /// /// 创建文件夹 /// public static void CreateFolder(string name, string parentName) { DirectoryInfo di = new DirectoryInfo(parentName); di.CreateSubdirectory(name); } /// /// 删除文件夹 /// public static bool DeleteFolder(string path) { try { Directory.Delete(path); return true; } catch { return false; } } /// /// 移动文件夹 /// public static bool MoveFolder(string oldPath, string newPath) { try { Directory.Move(oldPath, newPath); return true; } catch { return false; } } /// /// 复制文件夹 /// public static bool CopyFolder(string source, string destination) { try { String[] files; if (destination[destination.Length - 1] != Path.DirectorySeparatorChar) destination += Path.DirectorySeparatorChar; if (!Directory.Exists(destination)) Directory.CreateDirectory(destination); files = Directory.GetFileSystemEntries(source); foreach (string element in files) { if (Directory.Exists(element)) CopyFolder(element, destination + Path.GetFileName(element)); else File.Copy(element, destination + Path.GetFileName(element), true); } return true; } catch { return false; } } #endregion #region 检测文件 /// /// 判断是否为安全文件名 /// /// 文件名 public static bool IsSafeName(string strExtension) { strExtension = strExtension.ToLower(); if (strExtension.LastIndexOf(".") >= 0) { strExtension = strExtension.Substring(strExtension.LastIndexOf(".")); } else { strExtension = ".txt"; } string[] arrExtension = { ".htm", ".html", ".txt", ".js", ".css", ".xml", ".sitemap", ".jpg", ".gif", ".png", ".rar", ".zip" }; for (int i = 0; i < arrExtension.Length; i++) { if (strExtension.Equals(arrExtension[i])) { return true; } } return false; } /// /// 判断是否为不安全文件名 /// /// 文件名、文件夹名 public static bool IsUnsafeName(string strExtension) { strExtension = strExtension.ToLower(); if (strExtension.LastIndexOf(".") >= 0) { strExtension = strExtension.Substring(strExtension.LastIndexOf(".")); } else { strExtension = ".txt"; } string[] arrExtension = { ".", ".asp", ".aspx", ".cs", ".net", ".dll", ".config", ".ascx", ".master", ".asmx", ".asax", ".cd", ".browser", ".rpt", ".ashx", ".xsd", ".mdf", ".resx", ".xsd" }; for (int i = 0; i < arrExtension.Length; i++) { if (strExtension.Equals(arrExtension[i])) { return true; } } return false; } /// /// 判断是否为可编辑文件 /// /// 文件名、文件夹名 public static bool IsCanEdit(string strExtension) { strExtension = strExtension.ToLower(); if (strExtension.LastIndexOf(".") >= 0) { strExtension = strExtension.Substring(strExtension.LastIndexOf(".")); } else { strExtension = ".txt"; } string[] arrExtension = { ".htm", ".html", ".txt", ".js", ".css", ".xml", ".sitemap" }; for (int i = 0; i < arrExtension.Length; i++) { if (strExtension.Equals(arrExtension[i])) { return true; } } return false; } #endregion #region GetPhysicalPath(获取物理路径) /// /// 获取物理路径 /// /// 相对路径 /// public static string GetPhysicalPath(string relativePath) { if (string.IsNullOrWhiteSpace(relativePath)) { return string.Empty; } if (HttpContext.Current == null) { if (relativePath.StartsWith("~")) { relativePath = relativePath.Remove(0, 2); } return Path.GetFullPath(relativePath); } if (relativePath.StartsWith("~")) { return HttpContext.Current.Server.MapPath(relativePath); } if (relativePath.StartsWith("/") || relativePath.StartsWith("\\")) { return HttpContext.Current.Server.MapPath("~" + relativePath); } return HttpContext.Current.Server.MapPath("~/" + relativePath); } #endregion #region IsFileExists(检查某个文件是否真的存在) /// /// 检查某个文件是否真的存在 /// /// 需要检查的文件的路径(包括路径的文件全名) /// 返回true则表示存在,false为不存在 public static bool IsFileExists(string path) { return File.Exists(path); } #endregion #region IsDirectoryExists(检查文件目录是否真的存在) /// /// 检查文件目录是否真的存在 /// /// 需要检查的文件目录 /// 返回true则表示存在,false为不存在 public static bool IsDirectoryExists(string path) { try { return Directory.Exists(Path.GetDirectoryName(path)); } catch (Exception) { return false; } } #endregion #region FindLineTextFromFile(查找文件中是否存在匹配的内容) /// /// 查找文件中是否存在匹配的内容 /// /// 查找的文件流信息 /// 在文件中需要查找的行文本 /// 是否区分大小写,true为区分,false为不区分 /// 返回true则表示存在,false为不存在 public static bool FindLineTextFromFile(FileInfo fileInfo, string lineTxt, bool lowerUpper = false) { bool isTrue = false; //表示没有查询到信息 try { //首先判断文件是否存在 if (fileInfo.Exists) { var streamReader = new StreamReader(fileInfo.FullName); do { string readLine = streamReader.ReadLine(); //读取的信息 if (String.IsNullOrEmpty(readLine)) { break; } if (lowerUpper) { if (readLine.Trim() != lineTxt.Trim()) { continue; } isTrue = true; break; } if (readLine.Trim().ToLower() != lineTxt.Trim().ToLower()) { continue; } isTrue = true; break; } while (streamReader.Peek() != -1); streamReader.Close(); //继承自IDisposable接口,需要手动释放资源 } } catch (Exception) { isTrue = false; } return isTrue; } #endregion public const string FileKey = "ihlih*0037JOHT*)(PIJY*(()JI^)IO%"; //加密密钥 #region FileEncryptInfo(对文件进行加密) /// /// 对文件进行加密 /// 调用:FileEncryptHelper.FileEncryptInfo(Server.MapPath("~" +路径), Server.MapPath("~" +路径), FileHelper.FileEncrityKey) /// /// 需要加密的文件路径 /// 加密完成后存放的文件路径 /// 文件密钥 public static void FileEncryptInfo(string fileOriginalPath, string fileFinshPath, string fileKey) { //分组加密算法的实现 using (var fileStream = new FileStream(fileOriginalPath, FileMode.Open)) { var buffer = new Byte[fileStream.Length]; fileStream.Read(buffer, 0, buffer.Length); //得到需要加密的字节数组 //设置密钥,密钥向量,两个一样,都是16个字节byte var rDel = new RijndaelManaged { Key = Encoding.UTF8.GetBytes(fileKey), Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; ICryptoTransform cryptoTransform = rDel.CreateEncryptor(); byte[] cipherBytes = cryptoTransform.TransformFinalBlock(buffer, 0, buffer.Length); using (var fileSEncrypt = new FileStream(fileFinshPath, FileMode.Create, FileAccess.Write)) { fileSEncrypt.Write(cipherBytes, 0, cipherBytes.Length); } } } #endregion #region FileDecryptInfo(对文件进行解密) /// /// 对文件进行解密 /// 调用:FileEncryptHelper.FileDecryptInfo(Server.MapPath("~" +路径), Server.MapPath("~" +路径), FileHelper.FileEncrityKey) /// /// 传递需要解密的文件路径 /// 解密后文件存放的路径 /// 密钥 public static void FileDecryptInfo(string fileFinshPath, string fileOriginalPath, string fileKey) { using (var fileStreamIn = new FileStream(fileFinshPath, FileMode.Open, FileAccess.Read)) { using (var fileStreamOut = new FileStream(fileOriginalPath, FileMode.OpenOrCreate, FileAccess.Write)) { var rDel = new RijndaelManaged { Key = Encoding.UTF8.GetBytes(fileKey), Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; using (var cryptoStream = new CryptoStream(fileStreamOut, rDel.CreateDecryptor(), CryptoStreamMode.Write)) { var bufferLen = 4096; var buffer = new byte[bufferLen]; int bytesRead; do { bytesRead = fileStreamIn.Read(buffer, 0, bufferLen); cryptoStream.Write(buffer, 0, bytesRead); } while (bytesRead != 0); } } } } #endregion #region GetSolutionPath(得到解决方案目录适用于命令行控制台) public static string GetSolutionPath() { // return AppDomain.CurrentDomain.SetupInformation.ApplicationBase return Path.GetFullPath(@"../../../"); } #endregion }