| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709 |
- 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
- {
- /// <summary>
- /// 文件公共处理类
- /// </summary>
- public static class FileOperationHelper
- {
- public static string privateKey = "<RSAKeyValue><Modulus>k44zKgQwvGWgeyLzgBpY/0/PIX2MsWz2umEx53G74tz14rmplqtOozM+42TqZgTh3sX/iDTxa/rfhQizZmYIe3HvxkG7F5CGjnNTreQzFZM7odnHtHPK5LZTkXCm8kob6xlZd5w8A+Y5rlWas4dXpSquhEfGCGGENjydWT6Px+U=</Modulus><Exponent>AQAB</Exponent><P>z7F5KyVFLY9qRz4vp5JKTzN510O2csWI8uvTCx8DAt9jkJzTOGJYiFrlT0OIDDujF03fTCwkuBN9JObgAul6Xw==</P><Q>td/8jhHrSmCaunHwPYooDnwbhgnW1ZiXavZp+lXVAcZrIoGkzQUiSI2N1c6Jj2vPy0JYcYlGRsTQKJ0Nsa/sOw==</Q><DP>Ovh5HvcGHVmLI49UmI/A6ZwEDEr9krjjmZW75nx3rmkfLABbOLczzAOC+G6EQnTsacGClW4zPtDJx6CGGk2QoQ==</DP><DQ>RFGRIyTkB5pmROcL4XIGPfqstBr6El4xcsKBaMHZM8N+9wVQDJuDF1HlF41v6uoKskWHx45TUb4Ym0jzne2BhQ==</DQ><InverseQ>agTNLFUFg7tFIA6wOS30JP0wCQSinrWuDRl5SK1l55Rv2ssnWITDBd+5T9IuQwCqu8AWCm2zb06bkppBkY44dw==</InverseQ><D>GsLZiK9F34VW+741B3C/314sJNjOYYdvoBHsqRs5hkWo2rvthAQBuRucNkWhNWuBQ5QJajyf5IOVcl1HnDS5KNOzr0tzEMCm3LqdfS1cf7FAeytAREZd7aZUt4jRh249o5zu6lgCp/ITz3ZX8XX7eMMXq64GoWS55P8oTxawdqk=</D></RSAKeyValue>";
-
- /// <summary>
- /// 读取文件内容到字符串
- /// </summary>
- /// <param name="filepath">文件路径</param>
- /// <param name="mode">操作模式</param>
- /// <returns></returns>
- 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);
- }
- }
- /// <summary>
- /// 将字符串写入到文件
- /// </summary>
- /// <param name="strXML">字符串</param>
- /// <param name="filePath">文件路径</param>
- /// <param name="mode">文件操作模式</param>
- /// <returns></returns>
- 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);
- }
- }
- /// <summary>
- /// 获取文件夹下所有Xml文件名
- /// </summary>
- /// <param name="path"></param>
- /// <returns></returns>
- public static List<string> GetFileList(string path) {
- DirectoryInfo folder = new DirectoryInfo(path);
- List<string> files = new List<string>();
- foreach (FileInfo file in folder.GetFiles("*.xml"))
- {
- files.Add(file.Name);
- }
- return files;
- }
- /// <summary>
- /// 获取文件夹下所有文件名
- /// </summary>
- /// <param name="path"></param>
- /// <returns></returns>
- public static List<string> GetAllFileList(string path)
- {
- DirectoryInfo folder = new DirectoryInfo(path);
- List<string> files = new List<string>();
- foreach (FileInfo file in folder.GetFiles())
- {
- files.Add(file.Name);
- }
- return files;
- }
- /// <summary>
- /// 获取文件夹下所有文件夹名
- /// </summary>
- /// <param name="path"></param>
- /// <returns></returns>
- public static List<string> GetAllDirectoryList(string path)
- {
- DirectoryInfo folder = new DirectoryInfo(path);
- List<string> files = new List<string>();
- foreach (DirectoryInfo dir in folder.GetDirectories())
- {
- files.Add(dir.Name);
- }
- return files;
- }
- /// <summary>
- /// 文件重命名,直到不重名为止
- /// </summary>
- /// <param name="path"></param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 获取文件夹内
- /// 当前重名文件之后,还有多少个重名的文件
- /// </summary>
- /// <param name="fileNames"></param>
- /// <param name="i"></param>
- /// <returns></returns>
- public static int GetNumAfterThisFile(string[] fileNames, int i)
- {
- int num = 0;
- for (int y=0; y<i; y++)
- {
- //if (y>(i - (fileNames.Length - 1)))
- {
- if (File.Exists(fileNames[y]))
- {
- num++;
- }
- }
- }
- return num;
- }
- /// <summary>
- /// 目录下所有内容复制
- /// </summary>
- /// <param name="SourcePath">要Copy的文件夹</param>
- /// <param name="DestinationPath">要复制到哪个地方</param>
- /// <param name="overwriteexisting">是否覆盖</param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 删除目录及内部所有文件
- /// </summary>
- /// <param name="dir">要删除的目录</param>
- 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)
- {
- }
- }
- /// <summary>
- /// 判断指定文件夹及子文件夹内是否有文件正被打开
- /// 1.文件夹内有文件被打开 0.没有 -1.文件夹不存在
- /// </summary>
- /// <param name="path"></param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 计算文件的大小
- /// </summary>
- /// <param name="lengthOfDocument"></param>
- /// <returns></returns>
- 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");
- }
- /// <summary>
- /// 判断文件是word还是excel
- /// 1.word; 2.excel; 0.其他
- /// </summary>
- /// <param name="filePath"></param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 获取文件的创建时间
- /// </summary>
- /// <param name="filePath"></param>
- /// <returns></returns>
- public static string GetFileCreationTime(string filePath)
- {
- FileInfo fi = new FileInfo(filePath);
- if (fi != null)
- return fi.LastWriteTime.ToString();//创建时间同一分钟内可能会相同,不清楚机制,暂时调整为修改时间;
- else
- return "";
- }
- /// <summary>
- /// 判断文件夹内是否有同名文件
- /// </summary>
- /// <param name="name"></param>
- /// <param name="filePath"></param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 图片备份-本地图片
- /// </summary>
- /// <returns></returns>
- 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<string> imageList = new List<string>();
- 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<ZipXmlModel>(ReadStringFromFile(Application.StartupPath + "\\BackupImages\\backupImages.xml", FileMode.Open));
- if (zipXmlModel.picNameList == null)
- zipXmlModel.picNameList = new List<PicName>();
- 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>(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<ZipXmlModel>(ReadStringFromFile(Application.StartupPath + "\\BackupImages\\backupImages.xml", FileMode.Open));
- if(zipXmlModel.picNameList == null)
- zipXmlModel.picNameList = new List<PicName>();
- //图片名称添加到xml中
- PicName onePicName = new PicName();
- onePicName.name = nowName;
- zipXmlModel.picNameList.Add(onePicName);
- string xmlNotes = XmlSerializeHelper.XmlSerialize<ZipXmlModel>(zipXmlModel);
- WriteStringToFile(xmlNotes, Application.StartupPath + "\\BackupImages\\backupImages.xml", FileMode.Create);
- return true;
- }
- catch (Exception)
- {
- return false;
- }
- }
- else
- return false;
- }
- }
- /// <summary>
- /// 图片备份-内存图片
- /// </summary>
- /// <param name="bitmap"></param>
- /// <param name="bitName"></param>
- /// <returns></returns>
- 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<ZipXmlModel>(ReadStringFromFile(Application.StartupPath + "\\BackupImages\\backupImages.xml", FileMode.Open));
- if (zipXmlModel.picNameList == null)
- zipXmlModel.picNameList = new List<PicName>();
- //图片名称添加到xml中
- PicName onePicName = new PicName();
- onePicName.name = bitPath;
- zipXmlModel.picNameList.Add(onePicName);
- string xmlNotes = XmlSerializeHelper.XmlSerialize<ZipXmlModel>(zipXmlModel);
- WriteStringToFile(xmlNotes, Application.StartupPath + "\\BackupImages\\backupImages.xml", FileMode.Create);
- return true;
- }
- /// <summary>
- /// 恢复图片
- /// </summary>
- /// <returns></returns>
- public static List<string> 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<string> imageNameList = new List<string>();
- ZipXmlModel zipXmlModel = XmlSerializeHelper.DESerializer<ZipXmlModel>(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;
- }
- }
- /// <summary>
- /// 对待恢复的图片做处理
- /// </summary>
- /// <param name="imgList"></param>
- /// <returns></returns>
- public static List<string> MoveRestoreImages(List<string> 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<string> newPathList = new List<string>();
- 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();
- }
- /// <summary>
- /// 获取相机sn和名称,如果不存在
- /// </summary>
- /// <param name="path"></param>
- /// <param name="cameraSN"></param>
- /// <param name="cameraName"></param>
- /// <returns></returns>
- 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;
- }
-
- }
- }
|