Visual Studio 2022中WPF WebView2项目嵌入index.html资源遇阻求助
解决方案
1. 正确配置index.html的嵌入属性
- 将index.html添加到项目中(建议放在项目根目录或新建
Resources子文件夹) - 选中该文件,打开属性窗口:
- 设置生成操作为「嵌入的资源」
- 设置复制到输出目录为「不复制」
2. 获取正确的嵌入资源名称
嵌入资源的名称格式是[项目命名空间].[文件路径(含文件夹)].[文件名],举两个例子:
- 若项目命名空间是
WebView2Testing,文件在根目录,资源名就是WebView2Testing.index.html - 若文件在
Resources文件夹,资源名就是WebView2Testing.Resources.index.html
你可以通过以下代码打印所有可用的嵌入资源名来确认:
var assem = System.Reflection.Assembly.GetExecutingAssembly(); foreach (var name in assem.GetManifestResourceNames()) { Console.WriteLine(name); }
运行后就能看到你的index.html对应的资源名了。
3. 完整的读取与写入代码
把你的newProject方法修改为以下完整实现:
using System.IO; using System.Reflection; void newProject(string projDir) { // 替换为你实际的嵌入资源名称 string resourceName = "WebView2Testing.index.html"; string strHTML = string.Empty; using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) { if (stream == null) { throw new FileNotFoundException("未找到嵌入的资源文件", resourceName); } using (var reader = new StreamReader(stream)) { strHTML = reader.ReadToEnd(); } } // 确保目标目录存在 Directory.CreateDirectory(projDir); string targetPath = Path.Combine(projDir, "index.html"); File.WriteAllText(targetPath, strHTML); }
常见问题排查
如果还是获取不到资源流,检查以下几点:
- 确认文件的生成操作确实设为了「嵌入的资源」
- 资源名称是否和
GetManifestResourceNames()输出的完全一致(.NET6对资源名大小写敏感) - 项目命名空间是否正确(可在项目属性的「应用」标签里查看)
内容的提问来源于stack exchange,提问作者Spydee
相关产品推荐
相关产品推荐

