使用动态文件名读取存储在资源文件(resx)中的字符串
在我的C#应用程序中,我需要创建一个为每个客户定制的字符串.resx文件。
我想要做的是每次必须向我的客户提供我的应用程序时都要避免重新编译整个项目,所以我需要动态访问这个字符串。 那么,如果我只在执行时间记录文件名,我如何访问(在应用程序执行期间)resx文件?
从现在起我写了类似的东西:
Properties.Resources.MyString1
其中Resource是我的Resource.resx文件。 但是我需要这样的东西:
GetStringFromDynamicResourceFile("MyFile.resx", "MyString1");
可能吗?
谢谢马克
在你的情况下,这样的事情会有帮助吗?
Dictionary resourceMap = new Dictionary(); 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]; }
您可以将所需的资源放入一个单独的DLL(每个客户一个),然后使用Reflection动态提取资源:
Assembly ass = Assembly.LoadFromFile("customer1.dll"); string s = ass.GetManifestResource("string1");
我可能有错误的语法 – 它很早。 这里有一个潜在的警告:通过Reflection访问DLL会将DLL文件锁定一段时间,这可能会阻止您更新或替换客户机上的DLL。
当然有可能。 您需要阅读msdn中的ResouceSet类。 如果要直接加载.resx文件,可以使用ResxResourceSet 。
使用LINQ to SQL而不是在项目中引用System.Windows.Forms.ResXResourceReader类。
public string GetStringFromDynamicResourceFile(string resxFileName, string resource) { return XDocument .Load(resxFileName) .Descendants() .FirstOrDefault(_ => _.Attributes().Any(a => a.Value == resource))? .Value; }
并使用它:
GetStringFromDynamicResourceFile("MyFile.resx", "MyString1");