123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526 |
- 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 = "<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>
- /// 获取文件夹下所有文件名
- /// </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> GetAllImgList(string path)
- {
- DirectoryInfo folder = new DirectoryInfo(path);
- List<string> files = new List<string>();
- 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;
- }
- /// <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="index"></param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 文件重命名
- /// </summary>
- /// <param name="path"></param>
- /// <returns></returns>
- public static void reNameFile(string oldPath,string newPath)
- {
- if (File.Exists(oldPath))
- {
- // 改名方法
- FileInfo fi = new FileInfo(oldPath);
- fi.MoveTo(Path.Combine(newPath));
- }
- }
- /// <summary>
- /// 目录下所有内容复制
- /// </summary>
- /// <param name="SourcePath">要Copy的文件</param>
- /// <param name="DestinationPath">要复制到哪个地方</param>
- /// <param name="overwriteexisting">是否覆盖</param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 目录下所有内容复制
- /// </summary>
- /// <param name="SourcePath">要Copy的文件</param>
- /// <param name="DestinationPath">要复制到哪个地方(具体文件)</param>
- /// <param name="overwriteexisting">是否覆盖</param>
- /// <returns></returns>
- 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;
- }
- /// <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);
- }
- }
- 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;
- }
- 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();
- }
- /// <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, StringComparison.OrdinalIgnoreCase) >= 0);
- if (!string.IsNullOrEmpty(v))
- {
- cameraName = v.Split('-')[0];
- return true;
- }
- }
- return false;
- }
- catch (Exception)
- {
- }
- return false;
- }
- }
- }
|