无法加载文件或程序集SharpDX

时间:2014-01-10 02:54:43

标签: c# sharpdx easyhook

我使用easyhookSharpDX从DirectX游戏中获取fps数据。有时它有效。但是,当我下次启动它时(可能只是几分钟后),它会抛出异常System.IO.FileNotFoundException: Could not load file or assembly SharpDX

当我多次重启它时,它可以工作。为什么?有没有人和我一样有问题?

SharpDX版本:2.4.2

1 个答案:

答案 0 :(得分:0)

我不使用EasyHook,但以下代码也适用于您。而不是使用具有一些限制的ILMerge,请执行以下操作:

1)将签名的SharpDx.dll和所有其他所需的SharpDx程序集链接到您的项目。将“本地副本”属性设置为“False”。

2)将这些库添加到项目中(就像使用.cs文件一样)并将文件属性设置为“Embedded Resource”和“Do not copy to output folder”。确保这些文件与您在步骤1中链接的文件完全相同。

3)注入后,首先在入口点调用以下函数,如果找到,则从资源加载任意程序集(托管或非托管)。

private static void LoadAssemblyFromResources() {
    AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => {
         try {
             Assembly asm = Assembly.GetExecutingAssembly();
             string name = args.Name.Substring(0, args.Name.IndexOf(',')) + ".dll";
             string rsc = asm.GetManifestResourceNames().FirstOrDefault(s => s.EndsWith(name));
             if (rsc == null) return null;  //assembly not found in resources
             byte[] module;
             using (Stream stream = asm.GetManifestResourceStream(rsc)) {
                 if (stream == null) return null;
                 module = new byte[stream.Length];
                 stream.Read(module, 0, module.Length);
             }
             try {
                 return Assembly.Load(module); //Load managed assembly as byte array
             } catch (FileLoadException) { 
                 string file = Path.Combine(Path.GetTempPath(), name);
                 if (!File.Exists(file) || !module.SequenceEqual(File.ReadAllBytes(file)))
                     File.WriteAllBytes(file, module);
                 return Assembly.LoadFile(file); //Load unmanaged assembly as file
             }
         } catch {
             return null;
         }
     };
 }