Oun*_*ess 235
您应始终使用资源管理器而不是直接读取文件以确保考虑全球化.
using System.Collections;
using System.Globalization;
using System.Resources;
...
ResourceManager MyResourceClass = new ResourceManager(typeof(Resources /* Reference to your resources class -- may be named differently in your case */));
ResourceSet resourceSet = MyResourceClass.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
string resourceKey = entry.Key.ToString();
object resource = entry.Value;
}
Run Code Online (Sandbox Code Playgroud)
Svi*_*ish 26
在我的博客上发表了关于它的博文 :)简短的版本是,找到资源的全名(除非你已经知道它们):
var assembly = Assembly.GetExecutingAssembly();
foreach (var resourceName in assembly.GetManifestResourceNames())
System.Console.WriteLine(resourceName);
Run Code Online (Sandbox Code Playgroud)
要将所有这些用于某些事情:
foreach (var resourceName in assembly.GetManifestResourceNames())
{
using(var stream = assembly.GetManifestResourceStream(resourceName))
{
// Do something with stream
}
}
Run Code Online (Sandbox Code Playgroud)
要使用除执行程序之外的其他程序集中的资源,您只需使用Assembly该类的其他一些静态方法获取不同的程序集对象.希望能帮助到你 :)
ResXResourceReader rsxr = new ResXResourceReader("your resource file path");
// Iterate through the resources and display the contents to the console.
foreach (DictionaryEntry d in rsxr)
{
Console.WriteLine(d.Key.ToString() + ":\t" + d.Value.ToString());
}
Run Code Online (Sandbox Code Playgroud)
小智 7
// Create a ResXResourceReader for the file items.resx.
ResXResourceReader rsxr = new ResXResourceReader("items.resx");
// Create an IDictionaryEnumerator to iterate through the resources.
IDictionaryEnumerator id = rsxr.GetEnumerator();
// Iterate through the resources and display the contents to the console.
foreach (DictionaryEntry d in rsxr)
{
Console.WriteLine(d.Key.ToString() + ":\t" + d.Value.ToString());
}
//Close the reader.
rsxr.Close();
Run Code Online (Sandbox Code Playgroud)
看链接:微软的例子
在将资源.RESX文件添加到项目中的那一刻,Visual Studio将创建一个具有相同名称的Designer.cs,为您创建一个类,并将资源的所有项目作为静态属性.在键入资源文件的名称后,在编辑器中键入点时,可以看到资源的所有名称.
或者,您可以使用反射循环遍历这些名称.
Type resourceType = Type.GetType("AssemblyName.Resource1");
PropertyInfo[] resourceProps = resourceType.GetProperties(
BindingFlags.NonPublic |
BindingFlags.Static |
BindingFlags.GetProperty);
foreach (PropertyInfo info in resourceProps)
{
string name = info.Name;
object value = info.GetValue(null, null); // object can be an image, a string whatever
// do something with name and value
}
Run Code Online (Sandbox Code Playgroud)
显然,只有当RESX文件在当前程序集或项目的范围内时,此方法才可用.否则,请使用"pulse"提供的方法.
此方法的优点是您可以调用已为您提供的实际属性,并根据需要考虑任何本地化.但是,它相当多余,因为通常您应该使用类型安全的直接方法来调用资源的属性.