将多个资源文件加载到一个资源管理器中

时间:2014-11-27 18:39:14

标签: c# .net

我正在寻找一种方法来创建一个资源管理器,它将所有数据保存在多个资源文件中。这甚至可能吗?如果是的话对我有用,因为我有10个以上的翻译资源文件。我想为此创建一个包装类,并创建一个资源管理器,如果我使用rm.GetString("string");我从一个资源文件中获取此值。我可能认为这不是最好的想法,但是......如果你有任何好的想法,请在这里分享!

我正在尝试以下代码:

var rm = new ResourceManager("ProjectNameSpace.ResourceName",
    Assembly.GetExecutingAssembly());

通过这样做我只从我指定的文件加载资源:ProjectNameSpace.ResourceName,我是对的吗?

对于这种或不同的方法,有没有很好的解决方法?

1 个答案:

答案 0 :(得分:1)

这不完全是你所要求的,但也许它会有所帮助。这是我使用的程序中的一些简化的复制粘贴代码,它读取多个资源文件并创建资源文件中所有图标的组合字典。

   class Program
   {
      static void Main(string[] args)
      {
         IconManager.FindIconsInResources(Resources1.ResourceManager);
         //IconManager.FindIconsInResources(Resources2.ResourceManager);
         //IconManager.FindIconsInResources(Resources3.ResourceManager);

         Image iconImage = IconManager.GetIcon("Incors_office_building_16x16");
      }
   }


   public static class IconManager
   {
      private static readonly Dictionary<string, ResourceSet> _iconDictionary = 
                                                             new Dictionary<string, ResourceSet>();

      /// <summary>
      /// Method to read the resources info for an assembly and find all of the icons and add them 
      /// to the icon collection.
      /// </summary>
      public static void FindIconsInResources(ResourceManager resourceManager)
      {
         // Get access to the resources (culture shouldn't matter, but has to be specified)
         ResourceSet resourceSet = 
                   resourceManager.GetResourceSet(CultureInfo.GetCultureInfo("en-us"), true, true);
         if (resourceSet == null)
            throw new Exception("Unable to create ResourceSet.");

         // Top of loop to examine each resource object 
         foreach (DictionaryEntry dictionaryEntry in resourceSet)
         {
            // Check it's an icon (or some kind of graphic)
            if (!(dictionaryEntry.Value is Bitmap))
               continue;

            // Get the resource name, which is basically the filename without ".png" and with '-' 
            //  and blanks converted to '_'. Ignore .ico files.
            string resourceKey = (string)dictionaryEntry.Key;
            if (resourceKey.EndsWith("_ico", StringComparison.Ordinal))
               continue;

            // Add (or replace) the icon in the icon dictionary
            _iconDictionary[resourceKey] = resourceSet;
         }
      }


      /// <summary>
      /// Method to get an icon image from one of several resource files.
      /// </summary>
      public static Image GetIcon(string iconName)
      {
         ResourceSet resourceSet;
         _iconDictionary.TryGetValue(iconName, out resourceSet);
         if (resourceSet == null)
            return null;

         return (Image)resourceSet.GetObject(iconName);
      }
   }