如何:访问附属 DLL 中的资源

一旦创建了附属 DLL 并向其添加资源(图标、位图、资源字符串,等等),您的外接程序和其他自动化项目将立即可以使用这些资源了。 下面的过程将阐释如何执行此操作。

提示

显示的对话框和菜单命令可能会与“帮助”中的描述不同,具体取决于您当前的设置或版本。这些过程是使用当前的常规开发设置开发的。 若要更改设置,请在“工具”菜单上选择“导入和导出设置”。 有关更多信息,请参见 使用设置

访问附属 DLL 资源

  1. 打开 Visual Studio 并加载现有的外接程序项目或创建新的外接程序项目。

  2. 添加下面的代码示例,对其进行编译并运行它。

示例

以下是 Visual Studio 用于查找附属 DLL 的常规算法。 可以使用此代码确定确实生成了附属 DLL,并且它具有您期望的资源名称。

static void Main(string[] args)
{
    string path = @"<some path here>";
    System.Reflection.Assembly asm =    
    System.Reflection.Assembly.LoadFrom(path);
    // For enhanced security, use the LoadFrom overload 
    // System.Reflection.Assembly.LoadFrom(path, securityInfo);
    // where securityInfo is an instance of an Evidence object.
    System.Reflection.Assembly assemblyForResources = 
    asm.GetSatelliteAssembly(System.Threading.
    Thread.CurrentThread.CurrentCulture);
    System.IO.Stream stream =    
    assemblyForResources.GetManifestResourceStream
    (assemblyForResources.GetManifestResourceNames()[0]);
    ResourceReader resReader = new ResourceReader(stream);
    foreach (System.Collections.DictionaryEntry entry in resReader)
    {
        System.Windows.Forms.MessageBox.Show(entry.Key.ToString());
    }
}

编译代码

若要使用此示例,请创建一个 Visual C# 控制台应用程序,添加此段代码以代替 Main() 函数,并将路径变量设置为外接程序程序集的路径(而不是附属 DLL 的路径)。 运行时,您将看到附属 DLL 中的所有可用资源。

请参见

任务

演练:创建托管附属 DLL