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

C#控制台程序读取项目内文件路径遇NullReferenceException,求解决

解决C#控制台程序读取项目内文件路径的问题

你遇到的NullReferenceException是因为控制台程序不存在ASP.NET的HttpContext上下文,HttpContext.Current会返回null,自然无法调用Server.MapPath。下面是几种适合控制台程序的文件路径读取方案:

方案1:通过程序集获取执行目录

using System.IO;
using System.Reflection;

// 获取当前程序集所在的目录
string assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
// 拼接模板文件的完整路径
string templatePath = Path.Combine(assemblyDirectory, "EmailTemplate", "HODEmailTemplate.html");

方案2:通过AppDomain获取应用基目录

using System.IO;
using System;

// 获取应用程序的基目录(通常是bin/Debug或bin/Release)
string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
string templatePath = Path.Combine(baseDirectory, "EmailTemplate", "HODEmailTemplate.html");

关键注意事项

  • 右键项目中的HODEmailTemplate.html文件,在属性窗口设置复制到输出目录为「如果较新则复制」或「始终复制」,这样编译时文件会被同步到输出目录,程序才能找到它。

内容的提问来源于stack exchange,提问作者Edwin K Biju

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 08:22:11