You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PictureBox中显示嵌入式资源图片前检查其是否存在

问题分析与修复方案

你的代码存在两个核心问题:

  1. 资源名称匹配错误:嵌入资源的完整名称格式为[项目命名空间].[资源所在路径].[文件名],并非直接使用test.png
  2. Image赋值方式错误:不能直接将字符串(资源名)赋值给pictureBox1.Image,需要从资源流中加载生成Image对象

正确实现步骤

1. 确认资源属性设置

确保test.png的属性配置为:

  • 生成操作:嵌入的资源
  • 复制到输出目录:不复制

2. 修正后的代码实现

using System.Reflection;
using System.Drawing;

namespace GetResource
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 替换为你的项目命名空间+资源完整路径,示例中图片直接在项目根目录
            string resourceFullName = "GetResource.test.png";
            // 若图片在Resources文件夹下,路径应为GetResource.Resources.test.png
            
            Assembly assembly = Assembly.GetExecutingAssembly();
            // 检查资源是否存在并加载
            using (Stream stream = assembly.GetManifestResourceStream(resourceFullName))
            {
                if (stream != null)
                {
                    pictureBox1.Image = Image.FromStream(stream);
                }
                else
                {
                    MessageBox.Show("test.png资源不存在");
                }
            }
        }
    }
}

额外提示

  • 若不确定资源完整名称,可通过Assembly.GetExecutingAssembly().GetManifestResourceNames()打印所有嵌入资源名,找到对应图片的完整名称
  • 使用using语句自动释放资源流,避免内存泄漏

内容的提问来源于stack exchange,提问作者Oscar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 22:45:32