请问如何在 C# 程序中得到全局程序集缓存(Global Assembly Cache)中的内容?
也就是要在 C# 程序中获得 gacutil /l 命令的内容。
using System.Reflection;public static class Pub
{
  public static Assembly[] GetGAC()
  {
    Assebmly[] gac;
    // TODO ...
    return gac;
  }
}
也就是要完成上述程序。谢谢!

解决方案 »

  1.   

    自己模拟一个cmd命令就好了吧
      

  2.   

    以前写的在办公室电脑了  网上随便找了个看看行不 // 实例一个Process类,启动一个独立进程
                Process p = new Process();            // 设定程序名
                p.StartInfo.FileName = "cmd.exe";
                // 关闭Shell的使用
                p.StartInfo.UseShellExecute = false;
                // 重定向标准输入
                p.StartInfo.RedirectStandardInput = true;
                // 重定向标准输出
                p.StartInfo.RedirectStandardOutput = true;
                //重定向错误输出
                p.StartInfo.RedirectStandardError = true;
                // 设置不显示窗口
                p.StartInfo.CreateNoWindow = true;            // 启动进程
                string pingrst;            p.Start();            p.StandardInput.WriteLine("ping -n 1 " + strIp);
                p.StandardInput.WriteLine("exit");            // 从输出流获取命令执行结果
                string strRst = p.StandardOutput.ReadToEnd();
      

  3.   

    这可不符合要求。
    而且我要求的是得到一个 Assembly[] 数组,不是一行行的字符串。
      

  4.   

    模拟cmd命令,先获取GAC里dll文件,再通过反射路径下的DLL获取相关信息
    cd c:\windows\accembly\GAC_MSIL
    xcopy *.* c:\temp\ /e   
      

  5.   

    难道就没有不用模拟 cmd 命令的方法了吗?
    假设有如下应用:
    我想知道服务商提供的 ASP.NET 服务器上的 GAC 中是否已经安装了以下第三方的 Assembly,如果安装了的话,版本是多少?ICSharpCode.SharpZipLib, Version=0.85.5.452
    System.Data.SQLite, Version=1.0.61.0要知道,如果在服务商的服务器上,很多事情是不能做的,如 
    cd c:\windows\accembly\GAC_MSIL 
    xcopy *.* c:\temp\ /e  
    这些东东肯定是不行的。
      

  6.   

    试试吧,就是效率不高:        public static Assembly[] GetGAC()
            {
                List<Assembly> list = new List<Assembly>();
                foreach (string s in Directory.GetFiles(@"C:\Windows\assembly", "*.*", SearchOption.AllDirectories))
                {
                    try
                    {
                        Assembly ass = Assembly.LoadFrom(s);
                        if (ass != null)
                            list.Add(ass);
                    }
                    catch
                    {
                        continue;
                    }
                }
                return list.ToArray();
            }
      

  7.   

    msdnKnowledge Base  
    id=317540DOC: Global Assembly Cache (GAC) APIs Are Not Documented in the .NET Framework Software Development Kit (SDK) Documentation
      

  8.   

    GAC的管理貌似托管库只提供了程序集的安装接口.
    其它的则只有fusion的COM接口;刚查了下fusion的api写了
    一小段程序这段程序可以枚举GAC内所有程序集并打印出对应
    程序集的简单、未加密名称.如果要获得完整的程序集明则要调用
    IAssemblyName.GetDisplayName方法,总体来说和GetName
    差不多只是多了个flags,LZ可以根据需要自行调整自己的代码.
    具体可以参考.net SDK的非托管API参考中的合成接口一节.//gac.cs
    using System;
    using System.Text;
    using System.Runtime.InteropServices;[ComImport]
    [Guid("21b8916c-f28e-11d2-a473-00c04f8ef448")]
    [InterfaceType (ComInterfaceType.InterfaceIsIUnknown)]interface IAssemblyEnum
    {    IntPtr GetNextAssembly( 
            /* [in] */ IntPtr pvReserved,
            /* [out] */ out IAssemblyName ppName,
            /* [in] */ uint dwFlags);
        
        void Reset();
        
        void Clone( 
            /* [out] */ out IAssemblyEnum ppEnum);
        
    }[ComImport]
    [Guid("CD193BC0-B4BC-11d2-9833-00C04FC31D2E")]
    [InterfaceType (ComInterfaceType.InterfaceIsIUnknown)]interface IAssemblyName
    {
        void SetProperty( 
            /* [in] */ uint PropertyId,
            /* [in] */ IntPtr pvProperty,
            /* [in] */ uint cbProperty);
        
        void GetProperty( 
            /* [in] */ uint PropertyId,
            /* [out] */ IntPtr pvProperty,
            /* [out][in] */ out uint pcbProperty);
        
        void Finalize();
        
        void GetDisplayName( 
            /* [out] */ StringBuilder szDisplayName,
            /* [out][in] */ ref uint pccDisplayName,
            /* [in] */ uint dwDisplayFlags);
        
        void Reserved( 
            /* [in] */ ref Guid refIID,
            /* [in] */ IntPtr pUnkReserved1,
            /* [in] */ IntPtr pUnkReserved2,
            /* [in] */ string szReserved,
            /* [in] */ Int64 llReserved,
            /* [in] */ IntPtr pvReserved,
            /* [in] */ uint cbReserved,
            /* [out] */ IntPtr ppReserved);
        
        void GetName( 
            /* [out][in] */ ref uint lpcwBuffer,
            /* [out] */ StringBuilder pwzName);
        
        void GetVersion( 
            /* [out] */ out uint pdwVersionHi,
            /* [out] */ out uint pdwVersionLow);
        
        void IsEqual( 
            /* [in] */ IAssemblyName pName,
            /* [in] */ uint dwCmpFlags);
        
        void Clone( 
            /* [out] */out IAssemblyName pName);
        
    }
    class GacList
    {
    [DllImport ("fusion.dll")]
    static extern IntPtr CreateAssemblyEnum (out IAssemblyEnum  pEnum,IntPtr pUnkReserved,IntPtr pName,uint dwFlags,IntPtr  pvReserved);
    const uint ASM_CACHE_ZAP       = 0x01;
    const uint ASM_CACHE_GAC       = 0x02;
    const uint ASM_CACHE_DOWNLOAD  = 0x04;
    const uint ASM_CACHE_ROOT      = 0x08; static void Main ()
    {
    IAssemblyEnum gacEnum;
    //创建GAC程序集的枚举器
    CreateAssemblyEnum (out gacEnum,IntPtr.Zero,IntPtr.Zero,ASM_CACHE_GAC,IntPtr.Zero);
    {
    IAssemblyName asm;
    gacEnum.GetNextAssembly (IntPtr.Zero,out asm,0);

    while (asm != null)
    {
    StringBuilder sbuf = new StringBuilder(1024);
    uint ccbuf = 1024;
    //获取程序集显示名称
    asm.GetName (ref ccbuf,sbuf);
    //打印程序集名称
    Console.WriteLine (sbuf.ToString());
    //释放COM对象
    Marshal.ReleaseComObject (asm);
    //枚举下一个
    gacEnum.GetNextAssembly (IntPtr.Zero,out asm,0);
    }
    }
    Marshal.ReleaseComObject (gacEnum);
    }
    }
      

  9.   

    我这里运行后的部分输出:
    [code=BatchFile]
    C:\Users\Canon\Desktop\temp>gac
    BDATunePIA
    CustomMarshalers
    DTEParseMgd
    ISymWrapper
    mcstoredb
    mcupdate
    Mcx2Dvcs
    Microsoft.Build.VisualJSharp
    Microsoft.GroupPolicy.Interop
    Microsoft.Ink
    Microsoft.Interop.Security.AzRoles
    Microsoft.SqlServer.ActiveXScriptTaskUtil
    Microsoft.SqlServer.BatchParser
    Microsoft.SqlServer.BulkInsertTaskConnections
    Microsoft.SqlServer.DTSRuntimeWrap
    Microsoft.SqlServer.GridControl
    Microsoft.SqlServer.MgdSqlDumper
    Microsoft.SqlServer.Replication
    Microsoft.SqlServer.SQLTask
    Microsoft.TeamFoundation.WorkItemTracking.Client.QueryLanguage
    Microsoft.Transactions.Bridge.Dtc
    Microsoft.VisualC.VSCodeParser
    Microsoft.VisualC.VSCodeParser
    Microsoft.VisualStudio.Modeling.Diagrams.GraphObject
    Microsoft.VisualStudio.Modeling.Sdk.Diagrams.GraphObject
    Microsoft.Xna.Framework
    mnvapi
    mscorcfg
    mscorcfg
    mscorlib
    MWArray
    napcrypt
    naphlpr
    Policy.1.0.Microsoft.Ink
    Policy.1.0.Microsoft.Interop.Security.AzRoles
    Policy.1.2.Microsoft.Interop.Security.AzRoles
    Policy.1.7.Microsoft.Ink
    PresentationCore
    soapsudscode
    Sybase.PowerBuilder.ADO
    Sybase.PowerBuilder.Common
    Sybase.PowerBuilder.Core
    Sybase.PowerBuilder.DataWindow.Interop
    Sybase.PowerBuilder.DataWindow.Web
    Sybase.PowerBuilder.DataWindow.Win
    Sybase.PowerBuilder.Db
    Sybase.PowerBuilder.DbExt
    Sybase.PowerBuilder.Editmask.Interop
    Sybase.PowerBuilder.EditMask.Win
    Sybase.PowerBuilder.Graph.Core
    Sybase.PowerBuilder.Graph.Interop
    Sybase.PowerBuilder.Graph.Web
    Sybase.PowerBuilder.Graph.Win
    Sybase.PowerBuilder.Interop
    Sybase.PowerBuilder.RTC.Interop
    Sybase.PowerBuilder.RTC.Win
    Sybase.PowerBuilder.Web
    Sybase.Powerbuilder.WebService.Runtime
    Sybase.PowerBuilder.WebService.RuntimeRemoteLoader
    Sybase.PowerBuilder.WebService.WSDL
    Sybase.PowerBuilder.WebService.WSDLRemoteLoader
    Sybase.PowerBuilder.Win
    System.Data
    System.Data.OracleClient
    System.EnterpriseServices
    System.Printing
    System.Transactions
    System.Web
    vjscor
    VJSharpCodeProvider
    vjsjbc
    vjslib
    vjslibcw
    VJSSupUILib
    vjsvwaux
    vjswfc
    VjsWfcBrowserStubLib
    vjswfccw
    vjswfchtml
    WebDev.WebHost
    WebDev.WebHost
    1
    Accessibility
    ASP.BrowserCapsFactory
    AspNetMMCExt
    AspNetMMCExt.resources
    ComSvcConfig
    CppCodeProvider
    CRVsPackageLib
    CrystalDecisions.CrystalReports.Design
    CrystalDecisions.CrystalReports.Engine
    CrystalDecisions.CrystalReports.Engine.resources
    CrystalDecisions.Data.AdoDotNetInterop
    CrystalDecisions.KeyCode
    CrystalDecisions.ReportAppServer.ClientDoc
    CrystalDecisions.ReportAppServer.CommLayer
    CrystalDecisions.ReportAppServer.CommonControls
    CrystalDecisions.ReportAppServer.CommonObjectModel
    CrystalDecisions.ReportAppServer.Controllers
    CrystalDecisions.ReportAppServer.DataDefModel
    CrystalDecisions.ReportAppServer.DataSetConversion
    CrystalDecisions.ReportAppServer.ObjectFactory
    CrystalDecisions.ReportAppServer.ReportDefModel
    CrystalDecisions.ReportAppServer.XmlSerialize
    CrystalDecisions.ReportSource
    CrystalDecisions.ReportSource.resources
    CrystalDecisions.Shared
    CrystalDecisions.Shared.resources
    CrystalDecisions.VSDesigner
    CrystalDecisions.VSDesigner.resources
    CrystalDecisions.Web
    CrystalDecisions.Web.resources
    CrystalDecisions.Windows.Forms
    CrystalDecisions.Windows.Forms.resources
    cscompmgd
    dfsvc
    DotNetHelper2005
    ehCIR
    ehepg
    ehepgdat
    ehExtCOM
    ehexthost
    ehiExtCOM
    ehiExtens
    ehiPlay
    ehiProxy
    ehiReplay
    ehiUserXp
    ehiVidCtl
    ehiwmp
    ehiWUapi
    ehRecObj
    ehshell
    EventViewer
    EventViewer.Resources
    FSharp.Compiler
    FSharp.Compiler.CodeDom
    FSharp.Compiler.Server.Shared
    FSharp.Core
    FSharp.LanguageService
    FSharp.PowerPack
    FSharp.PowerPack.Linq
    FSharp.ProjectSystem.Base
    FSharp.ProjectSystem.FSharp
    FSharp.ProjectSystem.PropertyPages
    FSharp.VS.FSI
    iAnywhere.Data.SQLAnywhere
    iAnywhere.VSIntegration.SQLAnywhere
    iAnywhere.VSIntegration.SQLAnywhere.resources
    iAnywhere.VSIntegration.SQLAnywhere.resources
    iAnywhere.VSIntegration.SQLAnywhere.resources
    iAnywhere.VSIntegration.SQLAnywhere.resources
    iAnywhere.VSPackage.SQLAnywhere
    iAnywhere.VSPackage.SQLAnywhere.resources
    iAnywhere.VSPackage.SQLAnywhere.resources
    iAnywhere.VSPackage.SQLAnywhere.resources
    iAnywhere.VSPackage.SQLAnywhere.resources
    IEExecRemote
    IEHost
    IIEHost
    Interop.Dso
    Interop.PomInterfaces
    loadmxf
    mcstore
    MFCMIFC80
    Microsoft.AnalysisServices
    Microsoft.AnalysisServices.AdomdClient
    Microsoft.AnalysisServices.AdomdClient.resources
    Microsoft.AnalysisServices.DeploymentEngine
    Microsoft.AnalysisServices.DeploymentEngine.resources
    Microsoft.AnalysisServices.resources
    Microsoft.AnalysisServices.Xmla
    Microsoft.AnalysisServices.Xmla.resources
    Microsoft.Build.Conversion.v3.5
    Microsoft.Build.Conversion.v3.5.resources
    Microsoft.Build.Engine
    Microsoft.Build.Engine
    Microsoft.Build.Engine.resources
    Microsoft.Build.Engine.resources
    Microsoft.Build.Framework
    Microsoft.Build.Framework
    Microsoft.Build.Tasks
    Microsoft.Build.Tasks.resources
    Microsoft.Build.Tasks.v3.5
    Microsoft.Build.Tasks.v3.5.resources
    Microsoft.Build.Utilities
    microsoft.build.utilities.resources
    Microsoft.Build.Utilities.v3.5
    Microsoft.Build.Utilities.v3.5.resources
    Microsoft.CompactFramework.Build.Tasks
    Microsoft.CompactFramework.Build.Tasks
    MICROSOFT.COMPACTFRAMEWORK.BUILD.TASKS.resources
    MICROSOFT.COMPACTFRAMEWORK.BUILD.TASKS.resources
    Microsoft.CompactFramework.Design
    Microsoft.CompactFramework.Design.Model
    Microsoft.CompactFramework.Design.Model.resources
    Microsoft.CompactFramework.Design.PocketPC
    Microsoft.CompactFramework.Design.PocketPC.resources
    Microsoft.CompactFramework.Design.PocketPC2004
    Microsoft.CompactFramework.Design.PocketPC2004.resources
    Microsoft.CompactFramework.Design.resources
    Microsoft.CompactFramework.Design.SmartPhone
    Microsoft.CompactFramework.Design.SmartPhone.resources
    Microsoft.CompactFramework.Design.SmartPhone2004
    Microsoft.CompactFramework.Design.SmartPhone2004.resources
    Microsoft.CompactFramework.Design.WindowsCE
    Microsoft.DataTransformationServices.Controls
    Microsoft.DataTransformationServices.Controls.resources
    Microsoft.DataWarehouse.Interfaces
    Microsoft.DataWarehouse.Interfaces.resources
    Microsoft.ExceptionMessageBox
    Microsoft.ExceptionMessageBox.resources
    Microsoft.GroupPolicy.Reporting
    Microsoft.GroupPolicy.Reporting.Resources
    Microsoft.Ink.Resources
    Microsoft.JScript
    Microsoft.Jscript.resources
    Microsoft.ManagementConsole
    Microsoft.ManagementConsole.Resources
    Microsoft.MediaCenter
    Microsoft.MediaCenter.Shell
    Microsoft.MediaCenter.Sports
    Microsoft.MediaCenter.UI
    Microsoft.MSXML
    Microsoft.NetEnterpriseServers.ExceptionMessageBox
    Microsoft.NetEnterpriseServers.ExceptionMessageBox.resources
    Microsoft.Office.Tools.Common
    Microsoft.Office.Tools.Common.resources
    Microsoft.Office.Tools.Common.resources
    Microsoft.Office.Tools.Common.resources
    Microsoft.Office.Tools.Common.resources
    Microsoft.Office.Tools.Common.resources
    Microsoft.Office.Tools.Common.resources
    Microsoft.Office.Tools.Common.resources[/code]
      

  10.   

    貌似12楼的方法很不错,顺便跟大家说一下,Shfusion.dll位于 <Windows 文件夹>\Microsoft.NET\Framework\vx.x.xxxx 文件夹中,其中 x.x.xxxx 是您使用的 .NET Framework 的版本和内部版本号。
      

  11.   

    fusion API 才是标准答案
      

  12.   

    非常感谢。
    我试了一下,这个方法是可行的。
    只不过需要进一步根据 Assembly 的名称得到 Assembly 对象本身。
      

  13.   

    这个简单,GetDisplayName可以获得全名,
    你可以用它构造一个AssemblyName,然后传给Assembly.Load做参数就行了.
      

  14.   


    非常感谢。在 MSDN 文档中:IAssemblyName::GetDisplayName 方法获取此 IAssemblyName 对象引用的程序集的可读名称。
    HRESULT GetDisplayName (
            [out]      LPOLESTR  szDisplayName,
            [in, out]  LPDWORD   pccDisplayName,
            [in]       DWORD     dwDisplayFlags
    );
    参数:
    szDisplayName 
    [out] 包含所引用程序集名称的字符串缓冲区。pccDisplayName 
    [in, out] szDisplayName 的大小(以宽字符为单位),包含一个 null 结束符字符。dwDisplayFlags 
    [in] ASM_DISPLAY_FLAGS 值的按位组合,这些值会影响 szDisplayName 的功能。
    ASM_DISPLAY_FLAGS 枚举typedef enum {
            
        ASM_DISPLAYF_VERSION                 = 0x01,
        ASM_DISPLAYF_CULTURE                 = 0x02,
        ASM_DISPLAYF_PUBLIC_KEY_TOKEN        = 0x04,
        ASM_DISPLAYF_PUBLIC_KEY              = 0x08,
        ASM_DISPLAYF_CUSTOM                  = 0x10,
        ASM_DISPLAYF_PROCESSORARCHITECTURE   = 0x20,
        ASM_DISPLAYF_LANGUAGEID              = 0x40,
        ASM_DISPLAYF_RETARGET                = 0x80,
        ASM_DISPLAYF_CONFIG_MASK             = 0x100,
        ASM_DISPLAYF_MVID                    = 0x200,
        ASM_DISPLAYF_FULL                    = 
                          ASM_DISPLAYF_VERSION           | 
                          ASM_DISPLAYF_CULTURE           | 
                          ASM_DISPLAYF_PUBLIC_KEY_TOKEN  | 
                          ASM_DISPLAYF_RETARGET          | 
                          ASM_DISPLAYF_PROCESSORARCHITECTURE
            
    } ASM_DISPLAY_FLAGS;
      

  15.   

    ChrisAK 在 12 楼的解答已经很好了。
    但是,我想知道有没有不用非托管 API 的解决方案。
    因为 12 楼的程序在 Linux 操作系统上的 mono 环境下运行时报错:Unhandled Exception: System.DllNotFoundException: fusion.dll
      at (wrapper managed-to-native) GacList:CreateAssemblyEnum (IAssemblyEnum&,intptr,intptr,uint,intptr)
      at GacList.Main () [0x00000] 这样,如果服务商提供的 ASP.NET 服务器是运行 Linux 操作系统的话,就无法达到我们的目的。请各位大侠看看有没有只有托管代码的方法。如果没有新的解答的话,我将于明天晚上结贴。谢谢!
      

  16.   


    mono....
    没研究过.
    托管代码的方法估计没有.
    .net的类库好像只提供了往GAC里安装程序集的功能.LZ可以去研究下mono是怎么实现GAC的,然后照着写一个.
    运行时判断环境来选择用哪一块代码.