using System; using System.Collections; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; namespace CommonTool { public class FileFuns { /// /// 判断文件是否已经打开 Open /// /// /// public static bool IsFileOpen(string filePath) { if (!File.Exists(filePath)) { WriteLog.LogError(filePath + "文件都不存在!"); return true; } IntPtr vHandle = _lopen(filePath, OfReadwrite | OfShareDenyNone); if (vHandle == HfileError) { WriteLog.LogError(filePath + "文件被占用!"); return true; } CloseHandle(vHandle); WriteLog.LogInfo(filePath + "没有被占用!"); return false; } public static void DeleteFile(string filePath) { File.Delete(filePath); } /// /// 文件正在被使用 /// /// /// public static bool IsFileInUse(string fileName) { bool inUse; FileStream fs = null; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None); inUse = false; } catch { inUse = true; } finally { fs?.Close(); } return inUse;//true表示正在使用,false没有使用 } // Methods public static void AddSeachingFolder(string pcSeachingFolder) { pcSeachingFolder = GetFolder(pcSeachingFolder, false); if (pcSeachingFolder != "" && !SeachingFolders.Contains(pcSeachingFolder)) { SeachingFolders.Add(pcSeachingFolder); } } private static bool DemainSecurity() { bool flag1 = true; try { new PrincipalPermission("qwertyuiopasdfgh", "qwertyuiopasdfgh").Demand(); } catch (Exception) { flag1 = false; } return flag1; } public static bool FileExists(string pcFileName) { string text1 = GetFullPathFileName(pcFileName); return (text1 != ""); } public static string GetAssemblyFolder() { // ReSharper disable once AssignNullToNotNullAttribute FileInfo info1 = new FileInfo(Assembly.GetCallingAssembly().Location); return info1.DirectoryName; } public static string GetFolder(string pcFolder, bool plCreateFolder) { string text1 = pcFolder; text1 = text1.TrimEnd('\\') + @"\"; if (Directory.Exists(text1)) { return text1; } if (plCreateFolder) { try { Directory.CreateDirectory(text1); } catch (Exception) { text1 = ""; } return text1; } return ""; } public static string GetFullPathFileName(string pcFileName) { string text1 = ""; if (File.Exists(pcFileName)) { text1 = pcFileName; } else { foreach (string text2 in SeachingFolders) { string text3 = text2 + pcFileName; if (File.Exists(text3)) { text1 = text3; break; } } } if (text1 != "") { FileInfo info1 = new FileInfo(text1); text1 = info1.FullName; } return text1; } private static bool Open(string pcFileName) { bool flag1 = false; if (DemainSecurity()) { flag1 = Open(pcFileName, _key); } return flag1; } private static bool Open(string pcFileName, string pcSecurityCode) { //bool flag1 = false; Close(); string text1 = GetFullPathFileName(pcFileName); if ((pcSecurityCode != "qwertyuiopasdfgh") || (text1 == "")) { return false; } byte[] buffer1 = Encoding.ASCII.GetBytes(_key); byte[] buffer2 = Encoding.ASCII.GetBytes(_IV); FileStream stream1 = new FileStream(text1, FileMode.Open, FileAccess.Read); SymmetricAlgorithm algorithm1 = SymmetricAlgorithm.Create(); CryptoStream stream2 = new CryptoStream(stream1, algorithm1.CreateDecryptor(buffer1, buffer2), CryptoStreamMode.Read); MemoryStream stream3 = new MemoryStream(); byte[] buffer3 = new byte[0x1388]; int num1 = 0x1388; while (num1 == 0x1388) { num1 = stream2.Read(buffer3, 0, 0x1388); if (num1 > 0) { stream3.Write(buffer3, 0, num1); } } stream1.Close(); stream2.Close(); _reader = new StreamReader(stream3); return true; } public static string ReadAll() { string text1 = ""; if (_reader != null) { ((MemoryStream)_reader.BaseStream).Seek(offset: 0, loc: SeekOrigin.Begin); text1 = _reader.ReadToEnd(); } return text1; } public static string ReadAll(string pcFileName) { string text1 = ""; if (Open(pcFileName)) { text1 = ReadAll(); } return text1; } public static string ReadEncryptedFile(string pcFileName) { return ReadEncryptedFile(pcFileName, _IV); } public static string ReadEncryptedFile(string pcFileName, string pcSecurityCode) { string text1 = ""; string text2 = GetFullPathFileName(pcFileName); if (text2 != "") { byte[] buffer1 = Encoding.ASCII.GetBytes(pcSecurityCode); byte[] buffer2 = Encoding.ASCII.GetBytes(pcSecurityCode); FileStream stream1 = new FileStream(text2, FileMode.Open, FileAccess.Read); SymmetricAlgorithm algorithm1 = SymmetricAlgorithm.Create(); CryptoStream stream2 = new CryptoStream(stream1, algorithm1.CreateDecryptor(buffer1, buffer2), CryptoStreamMode.Read); MemoryStream stream3 = new MemoryStream(); byte[] buffer3 = new byte[0x1388]; int num1 = 0x1388; while (num1 == 0x1388) { num1 = stream2.Read(buffer3, 0, 0x1388); if (num1 > 0) { stream3.Write(buffer3, 0, num1); } } stream1.Close(); stream2.Close(); StreamReader reader1 = new StreamReader(stream3); stream3.Seek(0, SeekOrigin.Begin); text1 = reader1.ReadToEnd(); reader1.Close(); } return text1; } public static string ReadFileAsString(string pcFileName) { string text1 = ""; pcFileName = GetFullPathFileName(pcFileName); if (pcFileName != "") { FileStream fs = new FileStream(pcFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); StreamReader reader = new StreamReader(fs); //StreamReader reader = new StreamReader(pcFileName, Encoding.UTF8); text1 = reader.ReadToEnd(); reader.Close(); } return text1; } public static string ReadSection(string pcSectionName) { string text1 = ""; if (_reader != null) { string text2 = ReadAll(); pcSectionName = "[" + pcSectionName + "]"; int num1 = text2.ToUpper().IndexOf(pcSectionName.ToUpper(), StringComparison.Ordinal); if (num1 >= 0) { num1 = text2.IndexOf("\r\n", num1, StringComparison.Ordinal); } if (num1 < 0) { return text1; } num1 += 2; _reader.BaseStream.Seek(num1, SeekOrigin.Begin); for (string text4 = _reader.ReadLine(); text4 != null; text4 = _reader.ReadLine()) { if (((text4 != "") && (text4[0] == '[')) && (text4[text4.Length - 1] == ']')) { return text1; } text1 = text1 + ((text1 == "") ? "" : "\r\n") + text4; } } return text1; } public static string ReadSection(string pcSectionName, string pcFileName) { string text1 = ""; if (Open(pcFileName)) { text1 = ReadSection(pcSectionName); } return text1; } private static string ReadSection(string pcSectionName, string pcFileName, string pcSecurityCode) { string text1 = ""; if (Open(pcFileName, pcSecurityCode)) { text1 = ReadSection(pcSectionName); } return text1; } public static void SaveConnectionString(string pcConnStr) { if (pcConnStr != null && pcConnStr.Trim().Length > 0) { string lcFullName = GetFullPathFileName("RSDB.cfg"); SaveToFile(pcConnStr, lcFullName); } } public static string ReadSystemLicense() { return ReadSection("MachineId", "License", "qwertyuiopasdfgh"); } public static void RemoveSeachingFolder(string pcSeachingFolder) { if (SeachingFolders.Contains(pcSeachingFolder)) { SeachingFolders.Remove(pcSeachingFolder); } } /// /// 将图片保存到指定的文件中 /// /// /// /// public static bool SaveImageToFile(string pcFileName, Image poImage) { bool flag1 = false; if (pcFileName == "") { return false; } ImageFormat format1 = ImageFormat.Bmp; FileInfo info1 = new FileInfo(pcFileName); switch (info1.Extension.ToUpper().Trim()) { case "BMP": format1 = ImageFormat.Bmp; goto Label_0091; case "WMF": format1 = ImageFormat.Wmf; break; case "JPG": format1 = ImageFormat.Jpeg; break; } Label_0091: try { poImage.Save(pcFileName, format1); flag1 = true; } catch (Exception) { // ignored } return flag1; } /// /// 将字符串加密保存到指定的文件中 /// /// /// public static void SaveToFile(string pcStringToSave, string pcFileName) { FileStream stream1 = new FileStream(pcFileName, FileMode.OpenOrCreate, FileAccess.Write); stream1.SetLength(0); byte[] buffer1 = Encoding.ASCII.GetBytes(_key); byte[] buffer2 = Encoding.ASCII.GetBytes(_IV); SymmetricAlgorithm algorithm1 = SymmetricAlgorithm.Create(); CryptoStream stream2 = new CryptoStream(stream1, algorithm1.CreateEncryptor(buffer1, buffer2), CryptoStreamMode.Write); byte[] buffer3 = Encoding.ASCII.GetBytes(pcStringToSave); stream2.Write(buffer3, 0, buffer3.Length); stream1.Flush(); stream2.Close(); stream1.Close(); } //private static string TranslateFileFilter(string pcFileType) //{ // string text2; // string text1 = "All Files (*.*)|*.*"; // if ((text2 = pcFileType.ToUpper()) == null) // { // return text1; // } // text2 = string.IsInterned(text2); // if (text2 == "DLL") // { // return "Library files (*.dll)|*.dll"; // } // if (text2 == "RSC") // { // return "Configuration files (*.rsc)|*.rsc"; // } // if (text2 == "XLS") // { // return "Excel Files (*.xls)|*.xls"; // } // if (text2 != "IMAGE") // { // return text1; // } // return "Bitmap files (*.bmp)|*.bmp|JPG Files (*.jpg)|*.jpg|WMF Files (*.wmf)|*.wmf|All Files (*.*)|*.*"; //} /// /// 将字符串内容写入到文件中 /// /// 需要写入的字符串内容 /// 文件名称 /// public static bool WriteStringToFile(string pcStringToWrite, string pcFileName) { //bool flag1 = true; if (File.Exists(pcFileName)) { File.Delete(pcFileName); } StreamWriter writer1 = new StreamWriter(pcFileName, false, Encoding.UTF8); writer1.Write(pcStringToWrite); writer1.Flush(); writer1.Close(); return true; } /// /// 得到文件里的内容 /// /// 文件 /// 文件内容 public static string GetStream(string filePath) { FileStream stream1 = new FileStream(filePath, FileMode.Open); byte[] buffer1 = new byte[Convert.ToInt32(stream1.Length)]; stream1.Read(buffer1, 0, buffer1.Length); stream1.Close(); return Convert.ToBase64String(buffer1); } // Properties public static ArrayList SeachingFolders => _seachingFolders ?? (_seachingFolders = new ArrayList()); public static void Close() { _reader?.Close(); _reader = null; } // Fields [DllImport("kernel32.dll")] public static extern IntPtr _lopen(string lpPathName, int iReadWrite); [DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr hObject); const int OfReadwrite = 2; const int OfShareDenyNone = 0x40; //const int Buffersize = 0x1388; static readonly IntPtr HfileError = new IntPtr(-1); static readonly string _IV = "qwertyuiopasdfgh"; static readonly string _key = "qwertyuiopasdfgh"; static StreamReader _reader; static ArrayList _seachingFolders = new ArrayList(); #region 直接删除指定目录下的所有文件及文件夹(保留目录) /// ///直接删除指定目录下的所有文件及文件夹(保留目录) /// /// 文件夹路径 /// 执行结果 public static bool DeleteDir(string strPath) { try { strPath = @strPath.Trim().ToString();// 清除空格 if (System.IO.Directory.Exists(strPath))// 判断文件夹是否存在 { string[] strDirs = System.IO.Directory.GetDirectories(strPath);// 获得文件夹数组 string[] strFiles = System.IO.Directory.GetFiles(strPath);// 获得文件数组 foreach (string strFile in strFiles)// 遍历所有子文件夹 { //System.Diagnostics.Debug.Write(strFile + "-deleted"); System.IO.File.Delete(strFile);// 删除文件夹 } foreach (string strdir in strDirs)// 遍历所有文件 { //System.Diagnostics.Debug.Write(strdir + "-deleted"); System.IO.Directory.Delete(strdir, true);// 删除文件 } } return true;// 成功 } catch (Exception Exp) // 异常处理 { System.Diagnostics.Debug.Write(Exp.Message.ToString());// 异常信息 return false;// 失败 } } #endregion } }