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

.NET 7中通过.csproj嵌入资源后加载返回null问题求助

.NET 7嵌入式资源加载返回null的解决方法

问题描述

在C# .NET 7应用中通过.csproj嵌入this.txt、Build2.png等资源,尝试加载为字节数组时,所有加载资源的函数均返回null,无任何错误或警告。相关代码及配置如下:

发布命令

dotnet publish -r win-x86 -c Release --self-contained true /p:PublishSingleFile=true 

C#代码

using System.Reflection;
using System.IO;

namespace Program{
    class Program{
        static void Main(){
                    GetRes("Program.Build2.png");
        }

        public static byte[] GetRes(string resName)
                {
                    var assembly = typeof(MyLibrary.MyClass).GetTypeInfo().Assembly;
                    Stream resource = assembly.GetManifestResourceStream(resName);
                    return StreamToByteArray(resource);
        }

                public static byte[] StreamToByteArray(Stream input)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        input.CopyTo(ms);
                        return ms.ToArray();
                    }
                }
    }
}

.csproj配置

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <EmbeddedResource Include="this.txt" />
  </ItemGroup>
  <ItemGroup>
    <EmbeddedResource Include="Build2.png" />
  </ItemGroup>

</Project>

核心解决步骤

1. 修正程序集引用错误

代码中获取的是MyLibrary.MyClass所在的程序集,但嵌入式资源实际在主程序集(Program命名空间所属程序集)中,这是资源找不到的核心原因。将程序集获取代码改为:

var assembly = typeof(Program.Program).Assembly;

2. 确认资源的正确名称

嵌入式资源的全名格式为命名空间.文件名(若文件在子目录则为命名空间.子目录名.文件名)。可通过以下代码遍历当前程序集所有资源名称,确认目标资源的正确路径:

var assembly = Assembly.GetExecutingAssembly();
foreach (var resName in assembly.GetManifestResourceNames())
{
    Console.WriteLine(resName);
}

3. 处理单文件发布的资源包含问题

.NET 7单文件发布时,需确保嵌入式资源被正确包含,可在.csproj中添加配置:

<PropertyGroup>
  <IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
</PropertyGroup>

或在发布命令中追加参数:

dotnet publish -r win-x86 -c Release --self-contained true /p:PublishSingleFile=true /p:IncludeAllContentForSelfExtract=true

4. 代码空引用防护

原代码未处理resource为null的情况,会直接抛出空引用异常,需添加判断逻辑:

public static byte[] GetRes(string resName)
{
    var assembly = typeof(Program.Program).Assembly;
    using (Stream resource = assembly.GetManifestResourceStream(resName))
    {
        if (resource == null)
        {
            throw new FileNotFoundException("指定资源未找到", resName);
            // 或根据需求返回null/空字节数组
        }
        return StreamToByteArray(resource);
    }
}

5. 优化.csproj配置

合并重复的ItemGroup节点,简化配置:

<ItemGroup>
  <EmbeddedResource Include="this.txt" />
  <EmbeddedResource Include="Build2.png" />
</ItemGroup>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 10:35:31