从外部创建的 .resx 文件访问资源

Access Resources from Externally-Created .resx File

我的主要 Windows Forms(托管 C++)项目有一个 class 显示带有图块的图像,可以显示或隐藏这些图块以创建响应图。

我创建了一个单独的实用程序应用程序,它可以帮助我正确定位所有图像等。此应用程序是用 C# 编写的,并使用以下代码片段编写了一个包含图像数据和定位的 .resx 文件:

using(ResXResourceWriter resx = new ResXResourceWriter(sfd.FileName)) {
    resx.AddResource("Size", canvas.Size);
    List<int> IDs = canvas.IDs;
    resx.AddResource("IDList", IDs);
    resx.AddResource("BackgroundIndex", canvas.BackgroundIndex);
    foreach(int id in IDs) {
        String positionKey = String.Format("Position.id{0}", id);
        String visibilityKey = String.Format("Visibility.id{0}", id);
        String imageKey = String.Format("Image.id{0}", id);
        resx.AddResource(imageKey, canvas.TileImage(id));
        resx.AddResource(positionKey, canvas.TilePosition(id));
        resx.AddResource(visibilityKey, canvas.TileVisible(id));
    }
}

我可以在文本编辑器中打开 .resx 文件,看到它格式正确并且包含预期数据。

然后我将那个 .resx 文件添加到我的主应用程序项目中。现在我不知道如何获取其中的资源。我试过的代码是:

ResourceManager ^ image_rm = gcnew ResourceManager(
    "resx_file_name_without_extension", GetType()->Assembly);
ResourceSet ^ image_rs = image_rm->GetResourceSet(
    System::Globalization::CultureInfo::CurrentCulture, true, true);

在运行时,第二行(GetResourceSet 调用)抛出 System.Resources.MissingManifestResourceException 消息文本如下:

Resource load failure: Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "resx_file_name_without_extension.resources" was correctly embedded or linked into assembly "my_assembly" at compile time, or that all the satellite assemblies required are loadable and fully signed.

我怀疑我的问题是……嗯,我真的不知道。也许我没有在 ResourceManager 构造函数中使用正确的标识符。我尝试在文件的属性中明确设置 "Excluded From Build: No" 和 "Content: Yes",但这没有效果。

甚至可以将外部创建的 .resx 文件放入项目中并获取其中的资源吗?我绝对需要编译它;我无法运送带有悬空 .resx 文件的产品。我总是可以在 .cpp 文件中创建一组静态数据对象,但 .resx 方法似乎更优雅...

原来 this unanswered question 上的评论是秘诀。将根名称空间添加到标识符前面使 ResourceManager 高兴:

ResourceManager ^ image_rm = gcnew ResourceManager(
    "my_root_namespace.resx_file_name_without_extension", GetType()->Assembly);
ResourceSet ^ image_rs = image_rm->GetResourceSet(
    System::Globalization::CultureInfo::CurrentCulture, true, true);

编译器如何或为何决定将资源放置在该命名空间内对我来说仍然是个谜,但那是另一天的琐事。

我 link 的问题涉及在项目中使用 VS 创建的 .resx,而我的问题涉及添加一个外部创建的,所以我认为这是一种不同的情况,足以保证单独 Q/A.