在 .NET Core 3 中获取嵌入资源内容的类型安全方法



我正在使用.NET Core 3预览版6和Visual Studio 2019 16.2来创建WinForms应用程序。

在.NET Framework中,我使用类型安全的机制来加载资源,如下所示:

this.pictureBox1.BackgroundImage = global::MyNamespace.Properties.Resources.Image1;
this.textBox1.Text = global::MyNamespace.Properties.Resources.Script1;

但是在 .NET Core 3 中,我必须使用几种方法编写特殊的帮助程序类:

public static class EmbeddedResource
{
public static Image GetImage(String resourceName)
{
try
{
using (var stream = typeof(EmbeddedResource).GetTypeInfo().Assembly.GetManifestResourceStream(resourceName))
return Image.FromStream(stream);
}
catch(Exception exception)
{
throw new Exception($"Failed to read Embedded Resource {resourceName}");
}
}
public static String GetString(String resourceName)
{
try
{
using (var stream = typeof(EmbeddedResource).GetTypeInfo().Assembly.GetManifestResourceStream(resourceName))
using (var reader = new StreamReader(stream, Encoding.UTF8))
return reader.ReadToEnd();
}
catch(Exception exception)
{
throw new Exception($"Failed to read Embedded Resource {resourceName}");
}
}
}

并像这样使用它:

this.pictureBox1.BackgroundImage = EmbeddedResource.GetImage("MyNamespace.Image1.jpg");
this.textBox1.Text = EmbeddedResource.GetString("MyNamespace.Script1.sql");

有没有更好的方法(例如严格类型和资源名称错误安全)来做到这一点?

提前谢谢你。

Visual Studio 2019 16.2 具有对 Windows Forms .NET Core 项目的Resx文件的设计时支持。它与以前版本的 Visual Studio for Windows Forms 经典 .NET 项目中支持的功能相同。

这意味着您可以:

  1. 添加新项→选择资源文件并设置一个名称,如Resources.Resx,然后按添加。该文件将在设计模式下打开。(稍后要在设计模式下打开它,只需双击它。

  2. 通过将图像文件拖放到设计器中,将图像添加到设计器中。您还可以通过单击添加资源工具条下拉按钮并选择添加现有文件...添加图像。

然后,可以使用与图像同名的属性访问图像。例如,我创建了一个Properties文件夹并在该文件夹下创建了Resources.Resx,然后将MyImage.jpg添加到资源文件中,我可以这样使用它:

this.BackgroundImage = Properties.Resources.MyImage;

注意 - 在"属性"文件夹中为项目创建默认资源文件

  1. 右键单击项目→选择属性
  2. 在项目属性窗口中,选择"资源"(左侧,列表底部)。
  3. 在中心,您将看到一个链接此项目不包含默认资源文件。单击此处创建一个。单击链接,它将在Properties文件夹下为您的项目创建一个Resources.Resx文件。

最新更新