using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace SWS.Commons { public static class FileHelper { /// /// dwg等文件名是否合法。不带后缀 /// /// /// public static bool IsValidFileName(string fileName) { if (string.IsNullOrEmpty(fileName)) { return false; } // 获取 Windows 文件系统中不允许出现在文件名中的字符数组 char[] invalidChars = Path.GetInvalidFileNameChars(); // 检查文件名中是否包含非法字符 foreach (char c in invalidChars) { if (fileName.IndexOf(c) >= 0) { return false; } } // 检查是否为保留文件名 string[] reservedNames = { "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" }; string trimmedFileName = Path.GetFileNameWithoutExtension(fileName).Trim().ToUpper(); foreach (string reservedName in reservedNames) { if (trimmedFileName == reservedName) { return false; } } // 检查文件名是否以空格或句点结尾 if (fileName.TrimEnd().Length != fileName.Length || fileName.TrimEnd('.').Length != fileName.Length) { return false; } return true; } public static string GetFileMD5(string filePath) { if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath)) { throw new ArgumentException("文件路径无效或文件不存在", nameof(filePath)); } using (var md5 = MD5.Create()) // 创建 MD5 哈希算法实例 using (var stream = File.OpenRead(filePath)) // 打开文件流 { // 计算文件的 MD5 值 byte[] hashBytes = md5.ComputeHash(stream); // 将字节数组转换为十六进制字符串 StringBuilder sb = new StringBuilder(); foreach (var b in hashBytes) { sb.Append(b.ToString("x2")); // x2 格式化为两位小写十六进制数 } return sb.ToString(); // 返回 MD5 值的字符串 } } #region 检查文件是否被其他进程占用 /// /// 检查文件是否被其他进程占用 /// public static bool IsFileLocked(string filePath) { try { // 尝试以独占模式打开文件 using (FileStream fs = File.Open( filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) // FileShare.None 表示禁止共享 { return false; // 成功打开则未被占用 } } catch (IOException ex) { // 检查特定错误码 int errorCode = Marshal.GetHRForException(ex) & 0xFFFF; return errorCode == 32 || errorCode == 33; // 32: 共享冲突, 33: 进程锁定 } catch (UnauthorizedAccessException) { return true; // 无权限访问(可能被占用) } catch { return false; // 其他异常视为未被占用 } } #endregion } }