3

使用以下代码,我正在查询 GAC 以查看它是否安装了某个程序集。代码本身工作正常,但我只得到x86 GAC的结果。该程序集安装在 GAC GAC_64 和 GAC_32 中。

我该怎么做才能让“QueryAssemblyInfo”检查 x64 GAC?

  public bool IsInGac(string assemblyName)
  {
     ASSEMBLY_INFO assembyInfo = new ASSEMBLY_INFO();
     assembyInfo.cchBuf = 512;
     assembyInfo.currentAssemblyPath = new string('\0', assembyInfo.cchBuf);

     IAssemblyCache assemblyCache = null;

     IntPtr hr = NativeMethods.CreateAssemblyCache(out assemblyCache, 0);
     if (hr == IntPtr.Zero)
     {
        hr = assemblyCache.QueryAssemblyInfo(1, assemblyName, ref assembyInfo);
        if (hr != IntPtr.Zero)
        {
           return false;
        }

        return true;
     }

     return false;
  }

  internal static class NativeMethods
  {
     [DllImport("fusion.dll")]
     public static extern IntPtr CreateAssemblyCache(out IAssemblyCache ppAsmCache, int reserved);
  }

  [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae")]
  internal interface IAssemblyCache
  {
     int Dummy1();
     [PreserveSig]
     IntPtr QueryAssemblyInfo(int flags, [MarshalAs(UnmanagedType.LPWStr)]string assemblyName, ref ASSEMBLY_INFO assemblyInfo);
     int Dummy2();
     int Dummy3();
     int Dummy4();
  }

  [StructLayout(LayoutKind.Sequential)]
  internal struct ASSEMBLY_INFO
  {
     public int cbAssemblyInfo;
     public int assemblyFlags;
     public long assemblySizeInKB;

     [MarshalAs(UnmanagedType.LPWStr)]
     public String currentAssemblyPath;

     public int cchBuf;
  }
4

2 回答 2

2
    [DllImport("fusion.dll")]
    public static extern IntPtr CreateAssemblyCache(...)

此函数的返回类型是 HRESULT。这是一个int,而不是 C# 中的 IntPtr 。QueryAssemblyInfo() 声明也是如此。

当您以 AnyCPU 为目标时,这可能会导致随机故障。除此之外,代码很好,在我的机器上找到 GAC_64 中的程序集也没有问题。

在此处输入图像描述

于 2012-08-28T11:40:52.363 回答
0

自 .NET 1.1 起,这一切都可以通过System.EnterpriseServices程序集获得

var publisher = new System.EnterpriseServices.Internal.Publish();
publisher.GacInstall(@"C:\Temp\MyDLL.dll")

或者

publisher.GacRemove(@"C:\Temp\MyDLL.dll")
于 2017-01-25T21:42:14.693 回答