将dll注册到GAC中 - 但随后它不会显示在汇编窗口中

Ush*_*haP 2 c#

我有这个代码将dll注册到我的gac中

 Assembly asm = Assembly.LoadFrom(argument);
    RegistrationServices regAsm = new RegistrationServices();
    bool bResult = regAsm.RegisterAssembly(asm, AssemblyRegistrationFlags.SetCodeBase);
Run Code Online (Sandbox Code Playgroud)

并且工作正常,我对bResult忠诚,但是当我打开GAC窗口时,我希望看到那里的dll,但事实并非如此.谁能解释我为什么?

当我将dll放入GAC窗口时,我在那里看到它.

Han*_*ant 18

这很奇怪,它不是由.NET框架包装的.必要的融合声明随时可用.这段代码效果很好:

using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;

static class GacUtil {

    public static void InstallAssembly(string path, bool forceRefresh) {
        IAssemblyCache iac = null;
        CreateAssemblyCache(out iac, 0);
        try {
            uint flags = forceRefresh ? 2u : 1u;
            int hr = iac.InstallAssembly(flags, path, IntPtr.Zero);
            if (hr < 0) Marshal.ThrowExceptionForHR(hr);
        }
        finally {
            Marshal.FinalReleaseComObject(iac);
        }
    }

    public static void UninstallAssembly(string displayName) {
        IAssemblyCache iac = null;
        CreateAssemblyCache(out iac, 0);
        try {
            uint whatHappened;
            int hr = iac.UninstallAssembly(0, displayName, IntPtr.Zero, out whatHappened);
            if (hr < 0) Marshal.ThrowExceptionForHR(hr);
            switch (whatHappened) {
                case 2: throw new InvalidOperationException("Assembly still in use");
                case 5: throw new InvalidOperationException("Assembly still has install references");
                case 6: throw new System.IO.FileNotFoundException();    // Not actually raised
            }
        }
        finally {
            Marshal.FinalReleaseComObject(iac);
        }
    }


    [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae")]
    internal interface IAssemblyCache {
        [PreserveSig]
        int UninstallAssembly(uint flags, [MarshalAs(UnmanagedType.LPWStr)] string assemblyName, IntPtr pvReserved, out uint pulDisposition);
        [PreserveSig]
        int QueryAssemblyInfo(uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName, IntPtr pAsmInfo);
        [PreserveSig]
        int CreateAssemblyCacheItem(/* arguments omitted */);
        [PreserveSig]
        int CreateAssemblyScavenger(out object ppAsmScavenger);
        [PreserveSig]
        int InstallAssembly(uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pszManifestFilePath, IntPtr pvReserved);
    }

    [DllImport("mscorwks.dll", PreserveSig = false)]  // NOTE: use "clr.dll" in .NET 4+
    internal static extern void CreateAssemblyCache(out IAssemblyCache ppAsmCache, int reserved);
} 
Run Code Online (Sandbox Code Playgroud)

如果要使用此代码添加和删除程序集,请不要忘记在资源管理器窗口中按F5刷新视图.

  • @ScottLerch 不幸的是,它包装得太好了——无法知道卸载是否成功的结果。在 GacRemove() 中,丢弃 UninstallAssembly() 的结果;你会得到一个事件日志,但异常永远不会冒泡到调用代码。 (2认同)