Can I catch a missing dll error during application load in C#?

后端 未结 3 1089
你的背包
你的背包 2020-12-08 19:51

Is it possible to catch the exception when a referenced .dll cannot be found?

For example, I have a C# project with a reference to a third-party dll; if that dll c

相关标签:
3条回答
  • 2020-12-08 20:30

    Extending Josh's answer.

    Assemblies in .Net are loaded on demand by the CLR. Typically an assembly load won't be attempted until a method is JIT'd which uses a type from that assembly.

    If you can't catch the assembly load failure with a try/catch block in the main method, it's likely beceause you're using a type from the assembly within the try/catch. So the exception occurs before the main method is actually run.

    Try putting all of the code from the main method in a different function. Then call that function within the try/catch block and you should see the exception.

    0 讨论(0)
  • 2020-12-08 20:41

    You can use AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

      Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
        }
    

    To manually find the assembly if it can't find it automaticaly.

    0 讨论(0)
  • 2020-12-08 20:53

    For a Form Application put the try/catch in Program.cs. (Expanding on JaredPat's answer).

    Like this:

        [STAThread]
        static void Main()
        {
            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
    
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }
        }
    

    This will catch any missing DLL exceptions from your application. And they'll look similar to this:

    Could not load file or assembly 'TheGreatestDLLEver.Tribute, Version=0.0.0.2, Culture=neutral, PublicKeyToken=jamtoastbutter' or one of its dependencies. The system cannot find the file specified.

    0 讨论(0)
提交回复
热议问题