Read a string stored in a resource file (resx) with dynamic file name

后端 未结 4 1688
感情败类
感情败类 2021-02-14 14:12

In my C# application I need to create a .resx file of strings customized for every customer.

What I want to do is avoid recompiling the entire project every time I have

相关标签:
4条回答
  • 2021-02-14 14:14

    Will something like this help in your case?

    Dictionary<string, string> resourceMap = new Dictionary<string, string>();
    
    public static void Func(string fileName)
    {
        ResXResourceReader rsxr = new ResXResourceReader(fileName);        
        foreach (DictionaryEntry d in rsxr)
        {
            resourceMap.Add(d.Key.ToString(),d.Value.ToString());           
        }        
        rsxr.Close();
    }
    
    public string GetResource(string resourceId)
    {
        return resourceMap[resourceId];
    }
    
    0 讨论(0)
  • 2021-02-14 14:21

    You could put the needed resources into a separate DLL (one for each customer), then extract the resources dynamically using Reflection:

    Assembly ass = Assembly.LoadFromFile("customer1.dll");
    string s = ass.GetManifestResource("string1");
    

    I may have the syntax wrong - it's early. One potential caveat here: accessing a DLL through Reflection will lock the DLL file for a length of time, which may block you from updating or replacing the DLL on the client's machine.

    0 讨论(0)
  • 2021-02-14 14:25

    Of course it is possible. You need to read about ResouceSet class in msdn. And if you want to load .resx files directly, you can use ResxResourceSet.

    0 讨论(0)
  • 2021-02-14 14:32

    Use LINQ to SQL instead of referencing System.Windows.Forms.ResXResourceReader class in your project.

    public string GetStringFromDynamicResourceFile(string resxFileName, string resource)
    {
        return XDocument
                    .Load(resxFileName)
                    .Descendants()
                    .FirstOrDefault(_ => _.Attributes().Any(a => a.Value == resource))?
                    .Value;
    }
    

    And use it:

    GetStringFromDynamicResourceFile("MyFile.resx", "MyString1");
    
    0 讨论(0)
提交回复
热议问题