【问题标题】:Querying the x64-GAC查询 x64-GAC
【发布时间】:2017-01-26 05:42:14
【问题描述】:

通过以下代码,我正在查询 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;
  }

【问题讨论】:

  • 运行此代码的应用程序是为 x86 还是 x64 构建的?我很好奇它是否会查询与调用它的应用程序相对应的 GAC...
  • 这是一个普通的 .NET 应用程序,在 x64 机器上作为 64 位进程运行。

标签: c# .net winapi gac


【解决方案1】:
    [DllImport("fusion.dll")]
    public static extern IntPtr CreateAssemblyCache(...)

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

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

【讨论】:

  • 但您只会得到 一个 ASSEMBLY_INFO 作为结果。有 两个 程序集同名,一个在 GAC_32 中,一个在 GAC_64 中。
  • 这是 QueryAssemblyInfo() 不可避免的限制,它只能返回一个结果,并且不允许按架构过滤。请考虑使用 IAssemblyEnum。
  • 好的,这是有道理的。是否有一些如何在 C# 中使用它的示例?
  • 请使用谷歌查找示例。喜欢stackoverflow.com/questions/11050951/…
【解决方案2】:

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

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

或者

publisher.GacRemove(@"C:\Temp\MyDLL.dll")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多