Is there a way to loop through all the resources in a .resx
file in C#?
You should always use the resource manager and not read files directly to ensure globalization is taken into account.
using System.Collections;
using System.Globalization;
using System.Resources;
...
/* Reference to your resources class -- may be named differently in your case */
ResourceManager MyResourceClass =
new ResourceManager(typeof(Resources));
ResourceSet resourceSet =
MyResourceClass.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
string resourceKey = entry.Key.ToString();
object resource = entry.Value;
}
ResourceManager MyResourceClass = new ResourceManager("Resources.ResourceFileName", System.Reflection.Assembly.Load("App_GlobalResources"));
–
Vickery MyResourceClass
with Properties.Resources
. –
Monkhood Blogged about it on my blog :) Short version is, to find the full names of the resources(unless you already know them):
var assembly = Assembly.GetExecutingAssembly();
foreach (var resourceName in assembly.GetManifestResourceNames())
System.Console.WriteLine(resourceName);
To use all of them for something:
foreach (var resourceName in assembly.GetManifestResourceNames())
{
using(var stream = assembly.GetManifestResourceStream(resourceName))
{
// Do something with stream
}
}
To use resources in other assemblies than the executing one, you'd just get a different assembly object by using some of the other static methods of the Assembly
class. Hope it helps :)
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());
}
The minute you add a resource .RESX file to your project, Visual Studio will create a Designer.cs with the same name, creating a a class for you with all the items of the resource as static properties. You can see all the names of the resource when you type the dot in the editor after you type the name of the resource file.
Alternatively, you can use reflection to loop through these names.
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
}
This method is obviously only usable when the RESX file is in scope of the current assembly or project. Otherwise, use the method provided by "pulse".
The advantage of this method is that you call the actual properties that have been provided for you, taking into account any localization if you wish. However, it is rather redundant, as normally you should use the type safe direct method of calling the properties of your resources.
// 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();
see link: microsoft example
System.Windows.Forms
assembly and is not automatically added if you're using an MVC app –
Rufe If you want to use LINQ, use resourceSet.OfType<DictionaryEntry>()
. Using LINQ allows you, for example, to select resources based on their index (int) instead of key (string):
ResourceSet resourceSet = Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (var entry in resourceSet.OfType<DictionaryEntry>().Select((item, i) => new { Index = i, Key = item.Key, Value = item.Value }))
{
Console.WriteLine(@"[{0}] {1}", entry.Index, entry.Key);
}
With the nuget package System.Resources.ResourceManager
(v4.3.0) the ResourceSet
and ResourceManager.GetResourceSet
are not available.
Using the ResourceReader
, as this post suggest: "C# - Cannot getting a string from ResourceManager (from satellite assembly)"
It's still possible to read the key/values of the resource file.
System.Reflection.Assembly resourceAssembly = System.Reflection.Assembly.Load(new System.Reflection.AssemblyName("YourAssemblyName"));
String[] manifests = resourceAssembly.GetManifestResourceNames();
using (ResourceReader reader = new ResourceReader(resourceAssembly.GetManifestResourceStream(manifests[0])))
{
System.Collections.IDictionaryEnumerator dict = reader.GetEnumerator();
while (dict.MoveNext())
{
String key = dict.Key as String;
String value = dict.Value as String;
}
}
Simple read loop use this code
var resx = ResourcesName.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, false, false);
foreach (DictionaryEntry dictionaryEntry in resx)
{
Console.WriteLine("Key: " + dictionaryEntry.Key);
Console.WriteLine("Val: " + dictionaryEntry.Value);
}
Using LINQ to SQL:
XDocument
.Load(resxFileName)
.Descendants()
.Where(_ => _.Name == "data")
.Select(_ => $"{ _.Attributes().First(a => a.Name == "name").Value} - {_.Value}");
I put my PDF into the resources folder for an MVC 5 Razor project. This is how I opened the file:
public IActionResult ViewCCACH()
{
return GetDocumentLikeThis("FORM CC");
}
private IActionResult GetDocumentLikeThis(string likeThis)
{
ResourceManager MyResourceClass = new ResourceManager(typeof(Resources));
ResourceSet resourceSet = MyResourceClass.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
//ResourceManager resourceSet = new ResourceManager("ACH AUTH FORM CC Blank.pdf", System.Reflection.Assembly.Load("App_GlobalResources"));
foreach (DictionaryEntry entry in resourceSet)
{
string resourceKey = entry.Key.ToString();
object resource = entry.Value;
if (resourceKey.Contains(likeThis))
{
string RunningPath = AppDomain.CurrentDomain.BaseDirectory;
string FileName = string.Format("{0}Properties\\" + resourceKey + ".pdf", Path.GetFullPath(Path.Combine(RunningPath, @"..\..\..\")));
var fileStream2 = new FileStream(FileName, FileMode.Open, FileAccess.Read);
var fsResult2 = new FileStreamResult(fileStream2, "application/pdf");
return fsResult2;
}
}
return View();
}
The code in .cshtml was simple:
<a class="tablinks btn btn-primary m-2 pull-right" href="/Merchant/ViewCCACH" target="_blank">Download File</a>
© 2022 - 2024 — McMap. All rights reserved.