You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Vestris.ResourceLib修改.NET EXE图标时遇文件无法打开错误

解决Vestris.ResourceLib修改.NET EXE图标时的文件打开错误

问题重现

使用Vestris.ResourceLib库修改.NET EXE图标时,触发错误提示:The system cannot open the device or file specified.,已尝试关闭目标程序进程、检查文件权限、管理员权限运行、禁用Windows Defender等操作,问题仍未解决。

原代码:

// IconPath: ./icon.ico (Exists)
// OutputPath: ./test.exe (Exists)
IconFile iconFile = new IconFile(IconPath);
IconDirectoryResource iconDirectoryResource = new IconDirectoryResource(iconFile);
iconDirectoryResource.SaveTo(OutputPath);

可能的解决方案

1. 替换为绝对路径

相对路径可能因程序工作目录不匹配导致文件找不到,改用绝对路径加载文件:

string iconPath = Path.GetFullPath("./icon.ico");
string targetExePath = Path.GetFullPath("./test.exe");

IconFile iconFile = new IconFile(iconPath);
// 后续操作使用targetExePath

2. 采用正确的资源替换流程

直接调用SaveTo无法正确处理.NET EXE的资源结构,需先加载目标EXE的现有资源,替换后再保存:

string iconPath = Path.GetFullPath("./icon.ico");
string targetExePath = Path.GetFullPath("./test.exe");

using (ResourceInfo resourceInfo = new ResourceInfo())
{
    // 加载目标EXE的所有资源
    resourceInfo.Load(targetExePath);
    
    // 加载新图标文件
    IconFile iconFile = new IconFile(iconPath);
    IconDirectoryResource newIconRes = new IconDirectoryResource(iconFile);
    
    // 移除原有图标相关资源
    resourceInfo.RemoveResources(ResourceTypes.RT_GROUP_ICON);
    resourceInfo.RemoveResources(ResourceTypes.RT_ICON);
    
    // 添加新图标资源
    resourceInfo.AddResource(newIconRes);
    
    // 保存修改回原EXE
    resourceInfo.Save(targetExePath);
}

3. 排查文件隐性占用

除目标程序外,文件管理器预览、第三方安全工具等可能后台占用文件,可通过以下方式处理:

  • 复制目标EXE到临时目录,修改临时文件图标后替换原文件:
string tempExe = Path.GetFullPath("./temp_test.exe");
// 复制原文件到临时路径
File.Copy(targetExePath, tempExe, overwrite: true);

// 在临时文件上执行资源修改(使用上述ResourceInfo代码)
using (ResourceInfo resourceInfo = new ResourceInfo())
{
    resourceInfo.Load(tempExe);
    // ...移除旧图标、添加新图标...
    resourceInfo.Save(tempExe);
}

// 替换原文件
File.Delete(targetExePath);
File.Move(tempExe, targetExePath);

4. 更新Vestris.ResourceLib版本

旧版本库可能对.NET EXE的资源格式支持不完善,更新NuGet包到最新版本。

内容的提问来源于stack exchange,提问作者Blank

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 16:47:21