Catch DllNotFoundException不起作用

时间:2014-08-20 10:24:09

标签: c# dll twain dllnotfoundexception

我正在尝试将连接的扫描仪记录在电脑上。

我正在使用https://bitbucket.org/soukoku/ntwain中的NTwain.dll。

如果我在服务器上运行我的应用程序,来自ntwain的一些依赖dll无法加载,所以我将在运行时加载dll,如果它将失败,我只想返回一个空列表。在项目参考中没有提及NTwain。

问题: 如果我在exe文件夹中有NTwain.dll,我在服务器上运行应用程序崩溃。它不会返回空列表。如果我删除dll并运行应用程序,则返回空列表。

代码:

public class Scanner : IDB
    {

        private enum DataGroups : uint
        {
            None = 0,
            Control = 0x1,
            Image = 0x2,
            Audio = 0x4,
            Mask = 0xffff,
        }

        public string Name { get; private set; }
        public string ProductFamily { get; private set; }
        public string Version { get; private set; }

        public Scanner()
        {
            Name = String.Empty;
        }

        public static List<Scanner> getScanners()
        {

            List<Scanner> scanners = new List<Scanner>();

            try
            {
                Assembly assembly = Assembly.LoadFrom(Environment.CurrentDirectory + "\\NTwain.dll");
                Type tident = assembly.GetType("NTwain.Data.TWIdentity");
                Type tsession = assembly.GetType("NTwain.TwainSession");
                object appId = tident.GetMethod("CreateFromAssembly").Invoke(null, new object[] { DataGroups.Image, System.Reflection.Assembly.GetExecutingAssembly() });
                object session = Activator.CreateInstance(tsession, appId);
                tsession.GetMethod("Open", new Type[0]).Invoke(session, null);
                object sources = session.GetType().GetMethod("GetSources").Invoke(session, null);

                foreach (var item in (IEnumerable)sources)
                {
                    Scanner scanner = new Scanner();
                    scanner.Name = (string)item.GetType().GetProperty("Name").GetValue(item, null);
                    scanner.ProductFamily = (string)item.GetType().GetProperty("ProductFamily").GetValue(item, null);
                    object version = item.GetType().GetProperty("Version").GetValue(item, null);
                    scanner.Version = (string)version.GetType().GetProperty("Info").GetValue(version, null);
                    scanners.Add(scanner);
                }
                return scanners;
            }
            catch (Exception e)
            {
                return new List<Scanner>();
            }
        }
}

1 个答案:

答案 0 :(得分:0)

我猜想在代码中捕获DllNotFoundException:

如果你删除了dll,那么

Assembly assembly = Assembly.LoadFrom(Environment.CurrentDirectory + "\\NTwain.dll");

抛出一个DllNotFoundException,它被catch块捕获,它表示返回一个空列表(就像你说的那样工作)。

如果您不删除dll,则代码会成功通过上面的行。如果通过以下行启动了另一个线程,并且发生了一个未在该线程中捕获的错误,那么catch块将不会捕获该错误(无论它可能是什么)并且应用程序崩溃。