using PaintDotNet.Base.Functionodel; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Security.Principal; using System.Text; using System.Windows.Forms; using static PaintDotNet.Base.Functionodel.ZipXmlModel; namespace PaintDotNet.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); } } /// /// 获取文件夹下所有Xml文件名 /// /// /// 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 GetAllFileList(string path) { DirectoryInfo folder = new DirectoryInfo(path); List files = new List(); foreach (FileInfo file in folder.GetFiles()) { files.Add(file.Name); } return files; } /// /// 获取文件夹下所有文件夹名 /// /// /// public static List GetAllDirectoryList(string path) { DirectoryInfo folder = new DirectoryInfo(path); List files = new List(); foreach (DirectoryInfo dir in folder.GetDirectories()) { files.Add(dir.Name); } 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 i) { int num = 0; for (int y=0; y(i - (fileNames.Length - 1))) { if (File.Exists(fileNames[y])) { num++; } } } return num; } /// /// 目录下所有内容复制 /// /// 要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); } if (System.IO.File.Exists(dir)) { System.IO.File.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 bool BackupImages(string dir, ZipXmlModel zipXmlModel) { string backupDict = Application.StartupPath + "\\BackupImages";//固定的图片备份文件夹 if (!Directory.Exists(backupDict)) Directory.CreateDirectory(backupDict); if (Directory.Exists(dir))//传过来的是文件夹 { string[] fileNames = Directory.GetFiles(dir); if (fileNames.Count() == 0) return false; //判断是否是图片对象 List imageList = new List(); foreach (string fileName in fileNames) { try { //Image image = Image.FromFile(fileName); imageList.Add(fileName); } catch (Exception) { } } if (imageList.Count == 0) return false; else { ////ZipXmlModel zipXmlModel = new ZipXmlModel(); //if (System.IO.File.Exists(Application.StartupPath + "\\BackupImages\\backupImages.xml")) // zipXmlModel = XmlSerializeHelper.DESerializer(ReadStringFromFile(Application.StartupPath + "\\BackupImages\\backupImages.xml", FileMode.Open)); if (zipXmlModel.picNameList == null) zipXmlModel.picNameList = new List(); foreach (string imageName in imageList) { string nowName = backupDict + "\\" + Path.GetFileName(imageName); if (File.Exists(nowName)) { nowName = GetReNameFile(nowName); } try { File.Copy(imageName, nowName, true); } catch(Exception) { continue; } //图片名称添加到xml中 PicName onePicName = new PicName(); onePicName.name = nowName; zipXmlModel.picNameList.Add(onePicName); } string xmlNotes = XmlSerializeHelper.XmlSerialize(zipXmlModel); WriteStringToFile(xmlNotes, Application.StartupPath + "\\BackupImages\\backupImages.xml", FileMode.Create); return true; } } else { if (System.IO.File.Exists(dir))//传过来的是单独文件 { try { string nowName = backupDict + "\\" + Path.GetFileName(dir); if (File.Exists(nowName)) { nowName = GetReNameFile(nowName); } File.Copy(dir, nowName, true); //ZipXmlModel zipXmlModel = new ZipXmlModel(); //if (System.IO.File.Exists(Application.StartupPath + "\\BackupImages\\backupImages.xml")) // zipXmlModel = XmlSerializeHelper.DESerializer(ReadStringFromFile(Application.StartupPath + "\\BackupImages\\backupImages.xml", FileMode.Open)); if(zipXmlModel.picNameList == null) zipXmlModel.picNameList = new List(); //图片名称添加到xml中 PicName onePicName = new PicName(); onePicName.name = nowName; zipXmlModel.picNameList.Add(onePicName); string xmlNotes = XmlSerializeHelper.XmlSerialize(zipXmlModel); WriteStringToFile(xmlNotes, Application.StartupPath + "\\BackupImages\\backupImages.xml", FileMode.Create); return true; } catch (Exception) { return false; } } else return false; } } /// /// 图片备份-内存图片 /// /// /// /// public static bool BackupImages(Bitmap bitmap, string bitName, string filePath) { //压缩包不做处理 if (!string.IsNullOrEmpty(filePath) && Path.GetExtension(filePath) == ".tga") return false; string backupDict = Application.StartupPath + "\\BackupImages";//固定的图片备份文件夹 if (!Directory.Exists(backupDict)) Directory.CreateDirectory(backupDict); string bitPath = ""; //非本地图片 if (string.IsNullOrEmpty(filePath)) { bitPath = backupDict + "\\" + bitName + ".jpg"; } //本地图片 else { bitPath = backupDict + "\\" + bitName; } if (File.Exists(bitPath)) { bitPath = GetReNameFile(bitPath); } try { string extension = Path.GetExtension(bitPath); switch (extension) { case ".jpg": bitmap.Save(bitPath, System.Drawing.Imaging.ImageFormat.Jpeg); break; case ".jpeg": bitmap.Save(bitPath, System.Drawing.Imaging.ImageFormat.Jpeg); break; case ".png": bitmap.Save(bitPath, System.Drawing.Imaging.ImageFormat.Png); break; case ".bmp": bitmap.Save(bitPath, System.Drawing.Imaging.ImageFormat.Bmp); break; case ".gif": bitmap.Save(bitPath, System.Drawing.Imaging.ImageFormat.Gif); break; default: bitmap.Save(bitPath, System.Drawing.Imaging.ImageFormat.Jpeg); break; } } catch(Exception) { return false; } ZipXmlModel zipXmlModel = new ZipXmlModel(); if (System.IO.File.Exists(Application.StartupPath + "\\BackupImages\\backupImages.xml")) zipXmlModel = XmlSerializeHelper.DESerializer(ReadStringFromFile(Application.StartupPath + "\\BackupImages\\backupImages.xml", FileMode.Open)); if (zipXmlModel.picNameList == null) zipXmlModel.picNameList = new List(); //图片名称添加到xml中 PicName onePicName = new PicName(); onePicName.name = bitPath; zipXmlModel.picNameList.Add(onePicName); string xmlNotes = XmlSerializeHelper.XmlSerialize(zipXmlModel); WriteStringToFile(xmlNotes, Application.StartupPath + "\\BackupImages\\backupImages.xml", FileMode.Create); return true; } /// /// 恢复图片 /// /// public static List RestoreImages() { string backupDict = Application.StartupPath + "\\BackupImages";//固定的图片备份文件夹 if (!Directory.Exists(backupDict)) return null; else { string backupXml = backupDict + "\\backupImages.xml"; if (System.IO.File.Exists(backupXml)) { List imageNameList = new List(); ZipXmlModel zipXmlModel = XmlSerializeHelper.DESerializer(ReadStringFromFile(backupXml, FileMode.Open)); if(zipXmlModel.picNameList != null && zipXmlModel.picNameList.Count > 0) { foreach(PicName pic in zipXmlModel.picNameList) { imageNameList.Add(pic.name); } } return imageNameList; } else return null; } } /// /// 对待恢复的图片做处理 /// /// /// public static List MoveRestoreImages(List imgList) { string oldPath = Application.StartupPath + "\\BackupImages"; string newPath = Application.StartupPath + "\\BackupImagesTemp"; if (Directory.Exists(newPath)) DeleteFolder(newPath); try { Directory.Move(oldPath, newPath); } catch (Exception) { return null; } List newPathList = new List(); foreach (string n in imgList) { string oldImg = n.Replace("BackupImages", "BackupImagesTemp"); newPathList.Add(oldImg); } return newPathList; } 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); } /*else { //Console.WriteLine(fsinfo.FullName); //将得到的文件全路径放入到集合中 //list.Add(fsinfo.FullName); }*/ } } 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) >= 0); if(!string.IsNullOrEmpty(v)) { cameraName = v.Split('-')[0]; return true; } } return false; } catch { } return false; } } }