WpfApp/Utils/IconHelper.cs
2025-10-13 15:00:50 +08:00

87 lines
3.1 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.IO;
namespace WpfApp.Utils
{
public static class IconHelper
{
/// <summary>
/// 获取图标路径(智能搜索)
/// </summary>
/// <param name="iconFileName">图标文件名,例如 "FMSDGAUGE-main.ico",为空使用默认图标</param>
/// <param name="externalDirs">可选外部搜索目录</param>
/// <returns>图标绝对路径</returns>
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}");
}
/// <summary>
/// 获取图标目录路径(智能推断)
/// </summary>
/// <param name="externalDirs">可选外部搜索目录</param>
/// <returns>图标目录的绝对路径</returns>
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}");
}
/// <summary>
/// 在指定目录及子目录搜索文件
/// </summary>
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;
}
}
}