我可以使用System.Reflection(etc)来确定DLL文件是否受管理而不受管理?

时间:2012-08-29 13:32:10

标签: c#

  

可能重复:
  How to determine whether a DLL is a managed assembly or native (prevent loading a native dll)?
  Is this DLL managed or unmanaged?

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

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

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

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

2 个答案:

答案 0 :(得分:1)

  

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

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

答案 1 :(得分: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复制此内容。

相关问题