using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Security.Principal; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace SmartCoalApplication.Base.CommTool { public static class FileOperationHelper { public static string privateKey = "k44zKgQwvGWgeyLzgBpY/0/PIX2MsWz2umEx53G74tz14rmplqtOozM+42TqZgTh3sX/iDTxa/rfhQizZmYIe3HvxkG7F5CGjnNTreQzFZM7odnHtHPK5LZTkXCm8kob6xlZd5w8A+Y5rlWas4dXpSquhEfGCGGENjydWT6Px+U=AQAB

z7F5KyVFLY9qRz4vp5JKTzN510O2csWI8uvTCx8DAt9jkJzTOGJYiFrlT0OIDDujF03fTCwkuBN9JObgAul6Xw==

td/8jhHrSmCaunHwPYooDnwbhgnW1ZiXavZp+lXVAcZrIoGkzQUiSI2N1c6Jj2vPy0JYcYlGRsTQKJ0Nsa/sOw==Ovh5HvcGHVmLI49UmI/A6ZwEDEr9krjjmZW75nx3rmkfLABbOLczzAOC+G6EQnTsacGClW4zPtDJx6CGGk2QoQ==RFGRIyTkB5pmROcL4XIGPfqstBr6El4xcsKBaMHZM8N+9wVQDJuDF1HlF41v6uoKskWHx45TUb4Ym0jzne2BhQ==agTNLFUFg7tFIA6wOS30JP0wCQSinrWuDRl5SK1l55Rv2ssnWITDBd+5T9IuQwCqu8AWCm2zb06bkppBkY44dw==GsLZiK9F34VW+741B3C/314sJNjOYYdvoBHsqRs5hkWo2rvthAQBuRucNkWhNWuBQ5QJajyf5IOVcl1HnDS5KNOzr0tzEMCm3LqdfS1cf7FAeytAREZd7aZUt4jRh249o5zu6lgCp/ITz3ZX8XX7eMMXq64GoWS55P8oTxawdqk=
"; /// /// 读取文件内容到字符串 /// /// 文件路径 /// 操作模式 /// public static string ReadStringFromFile(string filepath, FileMode mode) { try { using (FileStream fs = new FileStream(filepath, mode)) { StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("utf-8")); return sr.ReadToEnd().Trim(); } } catch (Exception ex) { throw new Exception("", ex);// "文件读取失败", ex); } } /// /// 将字符串写入到文件 /// /// 字符串 /// 文件路径 /// 文件操作模式 /// public static bool WriteStringToFile(string strXML, string filePath, FileMode mode) { try { if (File.Exists(filePath)) { File.Delete(filePath); } FileStream fs = new FileStream(filePath, mode); byte[] data = System.Text.Encoding.UTF8.GetBytes(strXML); //开始写入 fs.Write(data, 0, data.Length); //清空缓冲区、关闭流 fs.Flush(); fs.Close(); return true; } catch (Exception ex) { throw new Exception("", ex); //("文件写入失败", ex); } } /// /// 获取文件夹下所有文件名 /// /// /// public static List GetFileList(string path) { DirectoryInfo folder = new DirectoryInfo(path); List files = new List(); foreach (FileInfo file in folder.GetFiles("*.xml")) { files.Add(file.Name); } return files; } /// /// 获取文件夹下所有图片 /// /// /// public static List GetAllImgList(string path) { DirectoryInfo folder = new DirectoryInfo(path); List files = new List(); files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Where(s => s.ToLower().EndsWith(".jpg") || s.ToLower().EndsWith(".jpeg") || s.ToLower().EndsWith(".ico") || s.ToLower().EndsWith(".png") || s.ToLower().EndsWith(".tif") || s.ToLower().EndsWith(".wmf") || s.ToLower().EndsWith(".bmp")).ToList(); return files; } /// /// 文件重命名,直到不重名为止 /// /// /// public static string GetReNameFile(string path) { string newName; int i = 1; do { newName = ""; newName += Path.GetDirectoryName(path); newName += "\\" + Path.GetFileNameWithoutExtension(path) + "-" + i + Path.GetExtension(path); i++; } while (File.Exists(newName)); return newName; } /// /// 获取文件夹内 /// 当前重名文件之后,还有多少个重名的文件 /// /// /// /// public static int GetNumAfterThisFile(string[] fileNames, int index) { int num = 0; for (int y = 0; y < index; y++) { if (File.Exists(fileNames[y])) { num++; } } return num; } /// /// 文件重命名 /// /// /// public static void reNameFile(string oldPath,string newPath) { if (File.Exists(oldPath)) { // 改名方法 FileInfo fi = new FileInfo(oldPath); fi.MoveTo(Path.Combine(newPath)); } } /// /// 目录下所有内容复制 /// /// 要Copy的文件 /// 要复制到哪个地方 /// 是否覆盖 /// public static bool CopyFile(string SourcePath, string DestinationPath, string dateTimeStr ,bool overwriteexisting) { bool ret = false; try { //复制单个文件用的 if (File.Exists(SourcePath)) { if (!string.IsNullOrEmpty(dateTimeStr)) { FileInfo flinfo = new FileInfo(SourcePath); flinfo.CopyTo(DestinationPath + dateTimeStr + "_" + flinfo.Name, overwriteexisting); } else { FileInfo flinfo = new FileInfo(SourcePath); flinfo.CopyTo(DestinationPath + "\\" + flinfo.Name, overwriteexisting); } } ret = true; } catch (Exception ex) { //DeleteFolder(DestinationPath); ret = false; } return ret; } /// /// 目录下所有内容复制 /// /// 要Copy的文件 /// 要复制到哪个地方(具体文件) /// 是否覆盖 /// public static bool CopyFilePath(string SourcePath, string DestinationPath, string dateTimeStr, bool overwriteexisting) { bool ret = false; try { SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\"; DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\"; if (Directory.Exists(SourcePath)) { if (Directory.Exists(DestinationPath) == false) Directory.CreateDirectory(DestinationPath); foreach (string fls in Directory.GetFiles(SourcePath)) { FileInfo flinfo = new FileInfo(fls); flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting); } foreach (string drs in Directory.GetDirectories(SourcePath)) { DirectoryInfo drinfo = new DirectoryInfo(drs); if (CopyDirectory(drs, DestinationPath + drinfo.Name, overwriteexisting) == false) ret = false; } } else { //复制单个文件用的 SourcePath = SourcePath.EndsWith(@"\") ? SourcePath.Substring(0, SourcePath.Length - 1) : SourcePath; if (File.Exists(SourcePath)) { FileInfo flinfo = new FileInfo(SourcePath); flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting); } } ret = true; } catch (Exception) { DeleteFolder(DestinationPath); ret = false; } return ret; } /// /// 目录下所有内容复制 /// /// 要Copy的文件夹 /// 要复制到哪个地方 /// 是否覆盖 /// public static bool CopyDirectory(string SourcePath, string DestinationPath, bool overwriteexisting) { bool ret = false; try { SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\"; DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\"; if (Directory.Exists(SourcePath)) { if (Directory.Exists(DestinationPath) == false) Directory.CreateDirectory(DestinationPath); foreach (string fls in Directory.GetFiles(SourcePath)) { FileInfo flinfo = new FileInfo(fls); flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting); } foreach (string drs in Directory.GetDirectories(SourcePath)) { DirectoryInfo drinfo = new DirectoryInfo(drs); if (CopyDirectory(drs, DestinationPath + drinfo.Name, overwriteexisting) == false) ret = false; } } else { //复制单个文件用的 SourcePath = SourcePath.EndsWith(@"\") ? SourcePath.Substring(0, SourcePath.Length - 1) : SourcePath; if (File.Exists(SourcePath)) { FileInfo flinfo = new FileInfo(SourcePath); flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting); } } ret = true; } catch (Exception) { DeleteFolder(DestinationPath); ret = false; } return ret; } /// /// 删除目录及内部所有文件 /// /// 要删除的目录 public static void DeleteFolder(string dir) { try { if (System.IO.Directory.Exists(dir)) { string[] fileSystemEntries = System.IO.Directory.GetFileSystemEntries(dir); for (int i = 0; i < fileSystemEntries.Length; i++) { string text = fileSystemEntries[i]; if (System.IO.File.Exists(text)) { System.IO.File.Delete(text); } else { DeleteFolder(text); } } System.IO.Directory.Delete(dir); } } catch (Exception) { } } /// /// 判断指定文件夹及子文件夹内是否有文件正被打开 /// 1.文件夹内有文件被打开 0.没有 -1.文件夹不存在 /// /// /// public static int IsFileOpened(string dir) { if (System.IO.Directory.Exists(dir)) { string[] fileSystemEntries = System.IO.Directory.GetFileSystemEntries(dir); for (int i = 0; i < fileSystemEntries.Length; i++) { string text = fileSystemEntries[i]; if (System.IO.File.Exists(text)) { try { System.IO.File.Move(text, text); } catch (Exception) { return 1; } } else { //递归时外层要先接收内层的结果,无法直接多层catch出去 if (IsFileOpened(text) == 1) return 1; } } return 0; } return -1; } /// /// 计算文件的大小 /// /// /// public static string GetLength(long lengthOfDocument) { if (lengthOfDocument < 1024) return string.Format(lengthOfDocument.ToString() + 'B'); else if (lengthOfDocument > 1024 && lengthOfDocument <= Math.Pow(1024, 2)) return string.Format(Math.Floor(lengthOfDocument / 1024.0).ToString() + "KB"); else if (lengthOfDocument > Math.Pow(1024, 2) && lengthOfDocument <= Math.Pow(1024, 3)) return string.Format(Math.Round(lengthOfDocument / 1024.0 / 1024.0, 2).ToString() + "M"); else return string.Format(Math.Round(lengthOfDocument / 1024.0 / 1024.0 / 1024.0, 2).ToString() + "GB"); } /// /// 判断文件是word还是excel /// 1.word; 2.excel; 0.其他 /// /// /// public static int IsFileWordOrExcel(string filePath) { if (!string.IsNullOrEmpty(filePath)) { string fileExtension = Path.GetExtension(filePath); if (fileExtension == ".docx" || fileExtension == ".doc") return 1; else if (fileExtension == ".xls" || fileExtension == ".xlsx") return 2; else return 0; } else return 0; } /// /// 获取文件的创建时间 /// /// /// public static string GetFileCreationTime(string filePath) { FileInfo fi = new FileInfo(filePath); if (fi != null) return fi.LastWriteTime.ToString();//创建时间同一分钟内可能会相同,不清楚机制,暂时调整为修改时间; else return ""; } /// /// 判断文件夹内是否有同名文件 /// /// /// /// public static bool IsFileNameExist(string name, string filePath) { if (System.IO.Directory.Exists(filePath)) { DirectoryInfo theFolder = new DirectoryInfo(filePath); FileInfo[] fileList = theFolder.GetFiles(); foreach (FileInfo fileItem in fileList) { if (Path.GetFileNameWithoutExtension(fileItem.FullName) == name) return true; } } return false; } public static void RecursionDirector(string dirs, TreeNode node) { //绑定到指定的文件夹目录 DirectoryInfo dir = new DirectoryInfo(dirs); //检索表示当前目录的文件和子目录 FileSystemInfo[] fsinfos = dir.GetFileSystemInfos(); //遍历检索的文件和子目录 foreach (FileSystemInfo fsinfo in fsinfos) { //判断是否为空文件夹   if (fsinfo is DirectoryInfo) { TreeNode temp = new TreeNode(); temp.Name = fsinfo.FullName; temp.Text = fsinfo.FullName; node.Nodes.Add(temp); //递归调用 RecursionDirector(fsinfo.FullName, temp); } } } public static string ReadFileOwner(string path) { var fs = System.IO.File.GetAccessControl(path); var sid = fs.GetOwner(typeof(SecurityIdentifier)); var ntAccount = sid.Translate(typeof(NTAccount)); return ntAccount.ToString(); } /// /// 获取相机sn和名称,如果不存在 /// /// /// /// /// public static bool CheckCameraSNAndReturnName(string path, string cameraSN, out string cameraName) { cameraName = null; try { byte[] buffer = File.ReadAllBytes(path); string keys = Encoding.UTF8.GetString(buffer); var bytes = Convert.FromBase64String(keys); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(privateKey); int encriptedChunckSize = rsa.KeySize / 8; int dataLength = bytes.Length; int iterations = dataLength / encriptedChunckSize; ArrayList arrayList = new ArrayList(); for (int i = 0; i < iterations; i++) { byte[] tempBytes = new byte[encriptedChunckSize]; System.Buffer.BlockCopy(bytes, encriptedChunckSize * i, tempBytes, 0, tempBytes.Length); System.Array.Reverse(tempBytes); arrayList.AddRange(rsa.Decrypt(tempBytes, false)); } var descrypt = (byte[])arrayList.ToArray(typeof(Byte)); string result = Encoding.UTF8.GetString(descrypt); if (result != null) { string[] arr = result.Split('|'); string v = arr.ToList().Find(a => a.IndexOf(cameraSN, StringComparison.OrdinalIgnoreCase) >= 0); if (!string.IsNullOrEmpty(v)) { cameraName = v.Split('-')[0]; return true; } } return false; } catch (Exception) { } return false; } } }