3

可能重复:
如何确定 DLL 是托管程序集还是本机(防止加载本机 dll)?
这个 DLL 是托管的还是非托管的?

我的场景:我正在开始将大量 DLL 资源从 C++ 迁移到 C# 托管代码的过程。这些 DLL 必须存在于一个公共目录中,并且它们不是静态链接(引用)的。相反,它们是根据需要使用 Assembly.LoadFile() 加载的。

为了确定哪些是新的(托管)DLL,我尝试使用 FileInfo 对象数组遍历目录中的文件,并为每个对象加载程序集。

当 DLL 是非托管 C++ DLL 之一时,加载程序集的尝试当然会失败。

那么,我的问题是,是否可以使用反射或其他方式检查 DLL 文件,并确定其托管/非托管性质。

4

2 回答 2

1

当 DLL 是非托管 C++ DLL 之一时,加载程序集的尝试当然会失败。

只要有一个函数使用 try/catch 块来尝试加载程序集,如果可以加载程序集,则返回 true,如果抛出适当类型的异常,则返回 false。

于 2012-08-29T13:34:35.813 回答
0

看来您可以使用 GetAssemblyName() 来尝试查询程序集元数据。如果调用失败,将抛出 BadImageException。

class TestAssembly
{
    static void Main()
    {

        try
        {
            System.Reflection.AssemblyName testAssembly =
                System.Reflection.AssemblyName.GetAssemblyName(@"C:\Windows\Microsoft.NET\Framework\v3.5\System.Net.dll");

            System.Console.WriteLine("Yes, the file is an assembly.");
        }

        catch (System.IO.FileNotFoundException)
        {
            System.Console.WriteLine("The file cannot be found.");
        }

        catch (System.BadImageFormatException)
        {
            System.Console.WriteLine("The file is not an assembly.");
        }

        catch (System.IO.FileLoadException)
        {
            System.Console.WriteLine("The assembly has already been loaded.");
        }
    }
}
/* Output (with .NET Framework 3.5 installed):
    Yes, the file is an assembly.
*/

如果您愿意阅读更多内容,我会无耻地从http://msdn.microsoft.com/en-us/library/ms173100.aspx复制此内容。

于 2012-08-29T13:38:56.410 回答