using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Resources; namespace WxOrder.Framework.Helpers; /// /// WPF 资源读取帮助类 /// 支持 Resource、Embedded Resource、Content 三种方式 /// public static class ResourceHelper { /// /// 从 WPF 应用程序资源中读取文本内容(Build Action = Resource) /// /// 相对路径,如 "Ctrls/PDDInvoice/Resources/invoice.js" /// 程序集名称,可选,默认使用当前程序集 /// 文件内容字符串 public static string GetResourceText(string relativePath, string assemblyName = null) { try { // 构建 pack URI string uriString; if (string.IsNullOrEmpty(assemblyName)) { // 当前程序集 uriString = $"pack://application:,,,/{relativePath}"; } else { // 指定程序集 uriString = $"pack://application:,,,/{assemblyName};component/{relativePath}"; } var uri = new Uri(uriString, UriKind.Absolute); StreamResourceInfo resourceInfo = Application.GetResourceStream(uri); if (resourceInfo == null) { throw new FileNotFoundException($"资源未找到: {relativePath}"); } using (var reader = new StreamReader(resourceInfo.Stream)) { return reader.ReadToEnd(); } } catch (Exception ex) { return ""; } } /// /// 从嵌入资源中读取文本内容(Build Action = Embedded Resource) /// /// 完整资源名称,如 "YourNamespace.Ctrls.PDDInvoice.Resources.invoice.js" /// 程序集,默认使用当前程序集 /// 文件内容字符串 public static string GetEmbeddedResourceText(string resourceName, Assembly assembly = null) { try { assembly ??= Assembly.GetExecutingAssembly(); using (var stream = assembly.GetManifestResourceStream(resourceName)) { if (stream == null) { throw new FileNotFoundException($"嵌入资源未找到: {resourceName}"); } using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } catch (Exception ex) { throw new InvalidOperationException($"读取嵌入资源失败: {resourceName}", ex); } } /// /// 从嵌入资源中读取文本内容,自动查找资源名称(支持部分匹配) /// /// 文件名,如 "invoice.js" /// 程序集,默认使用当前程序集 /// 文件内容字符串 public static string GetEmbeddedResourceTextByFileName(string fileName, Assembly assembly = null) { assembly ??= Assembly.GetExecutingAssembly(); // 查找匹配的资源名称 var resourceNames = assembly.GetManifestResourceNames(); var matchedName = Array.Find(resourceNames, name => name.EndsWith(fileName)); if (string.IsNullOrEmpty(matchedName)) { throw new FileNotFoundException($"未找到名为 {fileName} 的嵌入资源"); } return GetEmbeddedResourceText(matchedName, assembly); } /// /// 从文件系统读取文本内容(Build Action = Content) /// /// 文件物理路径或相对路径 /// 文件内容字符串 public static string GetFileText(string filePath) { try { if (!File.Exists(filePath)) { throw new FileNotFoundException($"文件未找到: {filePath}"); } return File.ReadAllText(filePath, System.Text.Encoding.UTF8); } catch (Exception ex) { throw new InvalidOperationException($"读取文件失败: {filePath}", ex); } } /// /// 读取 JS 资源(专门针对 JS 文件的便捷方法) /// /// JS 文件相对路径 /// JS 文件内容 public static string GetJavaScriptResource(string relativePath) { return GetResourceText(relativePath); } }