如何使用LinkedResource数组动态加载图片,缺失PNG文件采用备用路径
实现方案
核心思路
- 先将现有png文件的序号和对应路径存入字典,实现O(1)效率的存在性校验
- 确定需要加载的序号范围(示例取现有文件的最小到最大序号,也可自定义固定范围)
- 遍历所有序号,匹配到文件则用原路径,未匹配则使用预设备用路径,逐个生成
LinkedResource对象后存入数组
完整代码实现
// 你的原始路径获取代码 string[] AttachmentLocation = Directory.GetFiles(destinationPath, "*.png"); // 建立【序号-文件路径】映射字典 var fileSeqMapping = new Dictionary<int, string>(); foreach (var filePath in AttachmentLocation) { string fileNameNoExt = Path.GetFileNameWithoutExtension(filePath); // 提取文件名中的数字部分,兼容CC大小写 if (int.TryParse(fileNameNoExt.TrimEnd('C', 'c'), out int sequence)) { fileSeqMapping[sequence] = filePath; } } // 无任何匹配文件时直接返回空数组,可按需修改异常处理逻辑 if (!fileSeqMapping.Any()) { return Array.Empty<LinkedResource>(); } // 此处可自定义序号范围,比如固定加载1-10直接改为 int minSeq = 1; int maxSeq = 10; int minSeq = fileSeqMapping.Keys.Min(); int maxSeq = fileSeqMapping.Keys.Max(); // 替换为你的备用图片实际绝对路径 const string fallbackImagePath = @"C:\your_path\fallback.png"; // 批量生成LinkedResource数组 List<LinkedResource> resourceList = new List<LinkedResource>(); for (int currentSeq = minSeq; currentSeq <= maxSeq; currentSeq++) { string loadPath = fileSeqMapping.TryGetValue(currentSeq, out string originalPath) ? originalPath : fallbackImagePath; LinkedResource image = new LinkedResource(loadPath, "image/png"); image.ContentId = Guid.NewGuid().ToString(); resourceList.Add(image); } LinkedResource[] result = resourceList.ToArray();
注意事项
- 代码已经兼容文件名后缀大小写(如
1cc、2Cc均可正常识别) - 备用图片建议使用绝对路径,避免相对路径因工作目录变化导致找不到文件
- 如果需要生成指定范围的序号,直接修改
minSeq和maxSeq的赋值逻辑即可
内容的提问来源于stack exchange,提问作者saadmalik
相关产品推荐
相关产品推荐

