Could not load file or assembly SharpDX

2.4k views Asked by At

I use easyhook and SharpDX to get fps data from a DirectX game. Sometimes it works. However, when I start it next time (maybe just some minutes later), it throws the exception System.IO.FileNotFoundException: Could not load file or assembly SharpDX.

When I restart it for several times, it can work. Why? Does anyone have the same problems as mine?

SharpDX version:2.4.2

1

There are 1 answers

0
user1431279 On

I don't use EasyHook, but the following code should work for you too. Instead of using ILMerge, which has some limitations, do the following:

1) Link the signed copiy of SharpDx.dll and all other needed SharpDx assemblies to your project. Set the "Local Copy" property to "False".

2) Add those libraries to your project (as you would with .cs files) and set the properties of the files to "Embedded Resource" and "Don't copy to output folder". Make sure those files are exactly the same you linked in step 1.

3) After injecting, first call the following function in your entrypoint, which loads arbitrary assemblies (managed or unmanaged) from your resources if found.

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;
         }
     };
 }