DLL中的GUID(.NET)DLL、GUID、NET

2023-09-05 23:44:10 作者:是对我最起码的尊重

我不是非常有经验的在这方面的 - 所以我有几个问题。首先,做所有的.NET创建的DLL有自己的GUID?如果不是这样,我的问题是如何得到一个,它与DLL相关联。

I'm not very experienced in this area - so I've got a few questions. Firstly, do all .Net created DLLs have their own GUID? If not, my question is how do I get one and associate it with the DLL.

接下来的问题是,如何获取该DLL的GUID - 即。给定一个DLL路径(C:\一些\路径\到\ A \ file.dll)我怎么确定它的GUID?此外,有没有一种简单的方法来走另一条路(GUID - > DLL) - 我读过一些关于这一点,但很多是指VB6的DLL和COM的东西...这是否仍然适用到.NET的DLL ?

Then the question is, how do I get the GUID of that dll - ie. given a DLL path (c:\some\path\to\a\file.dll) how do I determine its GUID? Also, is there an easy way to go the other way (GUID -> DLL) - I've read a bit about this but a lot of it refers to VB6 DLLs and COM stuff...does this still apply to .Net DLLs?

更新:感谢您​​的答案。也许我问错了问题。我想为我的每一个DLL文件,一个唯一的ID,这样我可以参考他们在一个数据库中。我希望能够利用存储在数据库中的唯一ID,然后轻松地查找DLL并做一些东西吧。从什么样的答案已经说也许我不应该使用GUID,是有一个.net办法做到这一点呢?

Update: Thanks for the answers. Maybe I'm asking the wrong question. I want to have a unique ID for each of my DLL files, so that I can reference them in a database. I want to be able to take the unique ID stored in the database, and then easily find the DLL and do some stuff with it. From what the answers have said maybe I shouldn't be using a GUID, is there a .Net way to do this then?

推荐答案

要回答第二个问题(GUID - >组装),这是简单的,如果已经被加载的DLL,你只是想找到其中一个有一个GUID(如果任何),你可以简单地做

To answer the second question (Guid -> assembly) this is simple if the dll is already loaded and you just want to find which one had a guid (if any) you can simply do

using System;
using System.Reflection;
using  System.Runtime.InteropServices;

static Assembly FindAssemblyForGuid(Guid match)
{
    foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
    {
        object[]  attributes = a.GetCustomAttributes(typeof(GuidAttribute)) ;
        if ( attributes.Length > 0 ) 
        {
            foreach (GuidAttribute g in attributes )
            {
                if (g.Value == match)
                    return a;
            }
        }
    }
    return null; // failed to find it
}

如果你想这样做的不它被加载,你要么需要将其加载到一个临时的应用程序域,检查它,然后删除该应用程序域,或使用非托管自省API做同样的事情,但没有必要后,释放什么。

If you want to do it without it being loaded you would either need to load it into a temporary app domain, check it, then drop the app domain or use the unmanaged introspection api to do the same thing but with no need to release anything after.