如何在C#中遍历Resources.resx?

我想访问C#中的许多文件,而且如果不对路径进行硬编码,就无法成功访问。我不想指定确切的路径,因为该程序应独立于其位置运行。
我认为应该通过将文件添加到“资源”中来做到这一点,但是我找不到如何遍历这些文件的方法。我发现了几页有关读取.resx的页面,但似乎所有这些页面都只解决了通过名称访问一个特定资源的问题,或者使用了硬编码的路径。
我目前拥有的代码如下:

ResXResourceReader resourcesreader = new ResXResourceReader(Properties.Resources);

这会导致编译器错误“'资源'是一种类型,在给定的上下文中无效”。

奇怪的是,当我对路径进行硬编码时,在运行时出现错误。

ResXResourceReader resourcesreader = new ResXResourceReader(@"G:\Programming\C#\Contest Judging\Contest Judging\Properties\Resources.resx");
foreach (DictionaryEntry image in resourcesreader)

在最底端,引发了一个异常:

System.ArgumentException
  ResX file Could not find a part of the path 'G:\Programming\C#\Contest Judging\Contest Judging\bin\Resources\BugsyWPfeiffer 1.png'. Line 123,position 5. cannot be parsed.

Inner Exception 1:
XmlException: Could not find a part of the path 'G:\Programming\C#\Contest Judging\Contest Judging\bin\Resources\BugsyWPfeiffer 1.png'. Line 123,position 5.

Inner Exception 2:
DirectoryNotFoundException: Could not find a part of the path 'G:\Programming\C#\Contest Judging\Contest Judging\bin\Resources\BugsyWPfeiffer 1.png'.

我想知道为什么它会开始在bin\中查找,就像我通过Resources.resx进行Ctrl + F一样,却没有发生。

lynch123 回答:如何在C#中遍历Resources.resx?

您可以通过从生成的ResourceManager类中获取Resources来做到这一点:

// Change this if you want to use fetch the resources for a specific culture
var culture = CultureInfo.InvariantCulture;

var resourceManager = Properties.Resources.ResourceManager;
var resourceSet = resourceManager.GetResourceSet(culture,createIfNotExists: true,tryParents: true);
foreach (DictionaryEntry entry in resourceSet)
{
    Console.WriteLine($"{entry.Key}: {entry.Value}");
}

资源被编译到您的应用程序(或附属程序集)中,因此没有resx文件供您加载。

本文链接:https://www.f2er.com/2823662.html

大家都在问