gpt4 book ai didi

c# - 使用 Mono.cecil 修改程序集后出现 "System.IO.FileNotFoundException"错误

转载 作者:行者123 更新时间:2023-12-02 05:12:27 26 4
gpt4 key购买 nike

为了重现问题,我创建了这样一个简单的类,这个文件将被编译为“SourceDLL.dll”。

namespace SourceDll
{
public class Class1
{
static public int Add(int b, int c)
{
return b + c;
}
}
}

然后我用Mono.Cecil修改一下,我打开保存回来就好了。

namespace InstrumentSystemDll
{
class Program
{
static void Main(string[] args)
{
var fileName = args[0];
var assembly = AssemblyDefinition.ReadAssembly(string.Format(@"..\..\..\Dependences\{0}.dll", fileName));
Console.WriteLine(string.Format(@"..\..\..\Dependences\{0}.Patched.dll", fileName));
assembly.Write(string.Format(@"..\..\..\Dependences\{0}.Patched.dll", fileName));
}
}
}

我得到一个修改过的“SourceDll.Patched.dll”文件,然后我尝试使用这个文件。创建了一个控制台应用程序并引用了“SourceDll.Patched.dll”。

namespace TestInstrumentDll
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Class1.Add(1, 1));
}
}

不幸的是,我得到了这样的错误:

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or ass embly 'SourceDll, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified. at TestInstrumentDll.Program.Main(String[] args)

如果我切换到原始的 SourceDll.dll,它可以正常工作并按我们的预期打印数字“2”。

最佳答案

这与 Mono.Cecil 库无关。这与 CLR 将如何搜索程序集有关。程序集名称写入程序集的元数据,CLR 将查看元数据以找到程序集。您只需将程序集从 SourceDLL.dll 重命名为 SourceDLL2.dll,然后引用重命名的程序集(不涉及 Mono.Cecil!),即可轻松测试它。您可以看到您将获得完全相同的异常。

要使其工作,您需要在编写之前更改程序集名称:

var assembly = AssemblyDefinition.ReadAssembly(assemblyPath));
assembly.Name.Name += ".Patched";
assembly.Write(assemblyPath.Replace(".dll", ".Patched.dll"));

关于c# - 使用 Mono.cecil 修改程序集后出现 "System.IO.FileNotFoundException"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15198447/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com