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

VB.NET中File.ReadAllText()读取项目根目录HTML文件路径问题

解决方案

方法1:动态获取项目根目录构造路径

通过代码向上遍历目录结构,定位到和.sln同级的项目根目录,再拼接HTML文件路径:

using System.IO;
using System.Reflection;

// 方式一:从程序运行目录向上找两级
string projectRoot = Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).Parent.FullName;
// 方式二:从程序集文件位置向上找两级(兼容性更好)
// string assemblyPath = Assembly.GetExecutingAssembly().Location;
// string projectRoot = Directory.GetParent(assemblyPath).Parent.Parent.FullName;

string htmlFilePath = Path.Combine(projectRoot, "file.html");
string htmlContent = File.ReadAllText(htmlFilePath);

方法2:设置文件自动复制到输出目录

让HTML文件随编译同步到bin/debug目录,直接用文件名读取即可:

  1. 在Visual Studio里右键项目中的file.html,选择「属性」
  2. 将「复制到输出目录」设置为「始终复制」或「如果较新则复制」
  3. 读取代码简化为:
string htmlContent = File.ReadAllText("file.html");

方法3:修正App.Config配置路径

如果要保留配置文件的方式,需确保路径写法正确并正确读取:

  1. 在App.Config中添加配置项:
<configuration>
  <appSettings>
    <add key="HtmlFilePath" value="..\..\file.html" />
  </appSettings>
</configuration>
  1. 读取配置并构造完整路径(需先引用System.Configuration程序集):
using System.Configuration;
using System.IO;

string relativePath = ConfigurationManager.AppSettings["HtmlFilePath"];
string fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, relativePath);
string htmlContent = File.ReadAllText(fullPath);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 05:04:59