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\Icons");
// 先搜索项目目录
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}");
}
///
/// 在指定目录及子目录搜索文件
///
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;
}
}
}