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

如何解决MonoGame不用Content.Load加载图片时的System.IO.FileNotFoundException错误

问题原因&解决方案

1. 缺少文件后缀

你代码里写的文件路径是CoolBox,但实际图片文件都带有.png/.jpg/.bmp这类后缀,系统查找无后缀的文件自然会提示不存在。

2. 路径拼接不规范

硬编码/作为路径分隔符在Windows环境下可能出现适配问题,建议用.NET提供的Path.Combine方法自动适配系统路径分隔符。

3. 纹理重复加载的额外问题

你在LoadContent生命周期里已经调用过一次LoadTexture,但没有保存返回的纹理对象,反而在每帧执行的Draw方法里反复调用该方法加载纹理,会导致严重的性能损耗,还可能触发文件占用冲突。

4. 确认文件复制配置

选中项目里Content/Graphic目录下的CoolBox图片文件,在属性面板里把「复制到输出目录」选项设置为「如果较新则复制」,确保文件会被同步到编译后的bin目录下。

修正后的代码

首先调整LoadTexture方法,并且增加字段存储加载好的纹理:

// 增加字段存储加载完成的纹理,避免重复加载
private Texture2D _coolBoxTexture;

public Texture2D LoadTexture()
{
    string assemblyDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
    // 补全文件后缀,用Path.Combine拼接路径,后缀根据你实际的文件格式修改
    string fullPath = Path.Combine(assemblyDir, "Content", "Graphic", "CoolBox.png");

    using (FileStream fileStream = File.Open(fullPath, FileMode.Open))
    {
        return Texture2D.FromStream(EntityManager.graphicsDevice, fileStream);
    }
}

调整Game1里的调用逻辑:

protected override void LoadContent()
{
    spriteBatch = new SpriteBatch(GraphicsDevice);
    // 保存加载好的纹理到字段
    _coolBoxTexture = coolBox.LoadTexture();
}

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);

    spriteBatch.Begin();
    // 直接用预加载好的纹理绘制,不用每帧加载
    spriteBatch.Draw(_coolBoxTexture, new Rectangle(0, 0, 280, 210), Color.White);
    spriteBatch.End();

    base.Draw(gameTime);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:27:03