C# 在.NET Core 3中获取嵌入式资源内容的类型安全方法
我正在使用.NET Core 3 preview 6和Visual Studio 2019 16.2创建WinForms应用程序 在.NET Framework中,我使用类型安全机制加载资源,类似于:C# 在.NET Core 3中获取嵌入式资源内容的类型安全方法,c#,winforms,.net-core,resources,C#,Winforms,.net Core,Resources,我正在使用.NET Core 3 preview 6和Visual Studio 2019 16.2创建WinForms应用程序 在.NET Framework中,我使用类型安全机制加载资源,类似于: this.pictureBox1.BackgroundImage = global::MyNamespace.Properties.Resources.Image1; this.textBox1.Text = global::MyNamespace.Properties.Resources.Scr
this.pictureBox1.BackgroundImage = global::MyNamespace.Properties.Resources.Image1;
this.textBox1.Text = global::MyNamespace.Properties.Resources.Script1;
this.pictureBox1.BackgroundImage = EmbeddedResource.GetImage("MyNamespace.Image1.jpg");
this.textBox1.Text = EmbeddedResource.GetString("MyNamespace.Script1.sql");
但在.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 = global::MyNamespace.Properties.Resources.Image1;
this.textBox1.Text = global::MyNamespace.Properties.Resources.Script1;
this.pictureBox1.BackgroundImage = EmbeddedResource.GetImage("MyNamespace.Image1.jpg");
this.textBox1.Text = EmbeddedResource.GetString("MyNamespace.Script1.sql");
有没有更好的方法(例如严格键入和resourceName防错)来做到这一点
提前感谢。Visual Studio 2019 16.2为Windows Forms.NET核心项目的
Resx
文件提供了设计时支持。它与早期版本的Visual Studio for Windows Forms classic.NET项目中支持的功能相同
这意味着你可以:
Resources.Resx
,然后按Add。该文件将在设计模式下打开。(稍后要在设计模式下打开它,只需双击它。)Properties
文件夹,并在该文件夹下创建了Resources.Resx
,然后将MyImage.jpg
添加到资源文件中,我可以这样使用它:
this.BackgroundImage = Properties.Resources.MyImage;
注意-在属性文件夹中为项目创建默认资源文件
Properties
文件夹下创建一个Resources.Resx
文件哇,好极了。VisualStudio2019只缺少一项功能—WinForms Designer for.NET Core:)它位于。是的,我知道。谢谢。我得到了
。\\Resource\\webpages.txt;字符串,mscorlib,版本=4.0.0.0,区域性=neutral,PublicKeyToken=b77a5c561934e089;utf-8
而不是实际内容。它对你有用windows@Toolkit对不起,我找不到。如果您发现WinForms.NET Core存在问题,可以在此处进行归档: