using System; using System.IO; namespace WpfApp.Utils { public static class IconHelper { /// /// 获取图标路径(智能搜索) /// /// 图标文件名,例如 "FMSDGAUGE-main.ico",为空使用默认图标 /// 可选外部搜索目录 /// 图标绝对路径 public static string GetIconPath(string iconFileName = null, string[] externalDirs = null) { // 默认图标文件名 string defaultIconName = "FMSDGAUGE-main.ico"; iconFileName ??= defaultIconName; // 默认项目图标目录(相对于 EXE) string projectIconDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\..\src\public"); // 先搜索项目目录 string path = SearchDirectory(projectIconDir, iconFileName); if (!string.IsNullOrEmpty(path)) return path; // 再搜索外部目录 if (externalDirs != null) { foreach (var dir in externalDirs) { path = SearchDirectory(dir, iconFileName); if (!string.IsNullOrEmpty(path)) return path; } } // 都没找到就抛异常 throw new FileNotFoundException($"找不到图标文件: {iconFileName}"); } /// /// 获取图标目录路径(智能推断) /// /// 可选外部搜索目录 /// 图标目录的绝对路径 public static string GetIconDirectoryPath(string[] externalDirs = null) { // 默认项目图标目录(相对于 EXE) string projectIconDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\..\src\public"); string fullPath = Path.GetFullPath(projectIconDir); if (Directory.Exists(fullPath)) return fullPath; // 如果外部目录存在则返回第一个有效路径 if (externalDirs != null) { foreach (var dir in externalDirs) { if (Directory.Exists(dir)) return Path.GetFullPath(dir); } } // 否则抛异常 throw new DirectoryNotFoundException($"找不到图标目录: {fullPath}"); } /// /// 在指定目录及子目录搜索文件 /// private static string SearchDirectory(string rootDir, string fileName) { if (string.IsNullOrEmpty(rootDir) || !Directory.Exists(rootDir)) return null; var files = Directory.GetFiles(rootDir, fileName, SearchOption.AllDirectories); if (files.Length > 0) return Path.GetFullPath(files[0]); return null; } } }