代码之家  ›  专栏  ›  技术社区  ›  Tomas Vana

如何在不重新编译的情况下动态加载和切换web应用程序(ASP.NET)中的资源文件?

  •  1
  • Tomas Vana  · 技术社区  · 16 年前

    我希望将web应用程序的资源文件(包含标签文本等)存储在数据库中,以便以后能够动态编辑和创建它们(可能在UI中)。我的想法是把整个 资源文件 文件,然后根据当前用户登录应用程序或切换上下文时的语言和某些其他属性按需加载。重要的是,资源不仅依赖于用户的文化信息,而且还依赖于一些上下文信息,这些信息可以由用户切换,而无需关闭或再次打开(在我们的示例中称为“组”,与一组用户无关)。

    是否可以从外部源加载资源的内容,并在服务器不重新编译web应用程序的情况下简单地切换它们?我知道有一些接口,我可以连接并实现一个定制的资源提供者,它可以直接从数据库中读取数据,但是如果它能够以某种方式与resx文件一起工作,可能会使事情变得更容易。。

    3 回复  |  直到 16 年前
        1
  •  6
  •   Dänu    16 年前

    虽然已经很晚了,但因为目前还没有答案。

    System.Resources.ResourceReader resourceReader 
        = new System.Resources.ResourceReader("PathToResourceFile");
    

    System.Resources.ResourceReader resourceReader 
        = new System.Resources.ResourceReader(HttpContext.Current.Request.UserLanguages[0] 
        + ".resource");
    

    编辑:

    看看这个 link .

        2
  •  3
  •   Luke Karski    10 年前

    这个问题已经问了6年了,但我还是要回答:)

    阅读 .雷斯 文件,您需要使用 System.Resources.ResXResourceReader 来自 System.Windows.Forms.dll

    这是很好的解释 here

    using (ResXResourceReader resxReader = new ResXResourceReader(@".\CarResources.resx"))
    {
        foreach (DictionaryEntry entry in resxReader) {
            // ...
        } 
    }
    
        3
  •  0
  •   Nigel Shaw    13 年前

    当然,您可以很容易地做到这一点,而且它适用于直接的XML文件。您不需要使用resx文件。

    /// <summary>
    /// Sets or replaces the ResourceDictionary by dynamically loading
    /// a Localization ResourceDictionary from the file path passed in.
    /// </summary>
    /// <param name="resourceDictionaryFile">The resource dictionary to use to set/replace
    /// the ResourceDictionary.</param>
    private void SetCultureResourceDictionary(String resourceDictionaryFile)
    {
        // Scan all resource dictionaries and remove, if it is string resource distionary
        for ( int index= 0; index < Resources.MergedDictionaries.Count; ++index)
        {
            // Look for an indicator in the resource file that indicates the resource is
            // swappable. For instance in our files the header contains this: 
            // <sys:String x:Key="ResourceDictionaryName">Resources-en-CA</sys:String> 
            if (Resources.MergedDictionaries[index].Contains("ResourceDictionaryName"))
            {
                if ( File.Exists(resourceDictionaryFile) )
                {
                    Resources.MergedDictionaries.Remove(Resources.MergedDictionaries[index]);
                }
            }
        }
    
        // read required resource file to resource dictionary and add to MergedDictionaries collection
        ResourceDictionary newResourceDictionary =  new ResourceDictionary();
        newResourceDictionary.Source = new Uri(resourceDictionaryFile);
        Resources.MergedDictionaries.Add(newResourceDictionary);
    }
    
    推荐文章