加载XML文件触发System.IO.FileNotFoundException,求问题排查
加载XML文件触发FileNotFoundException的问题分析
问题情况
FileA与FileB位于同一文件夹,从FileA中加载XML文件FileB时触发System.IO.FileNotFoundException异常。
FileA代码
public class FileA { private XmlDocument Doc; public FileA() { var filePath= "FileB.xml"; Doc = new XmlDocument(); Doc.Load(filePath); // 此处触发异常 - FileNotFound } }
VS项目结构
- Solution 'Items' - Server - bin - debug - net7.0 -> 包含exe文件 - MyFiles -> FileB.xml已复制到此文件夹 - Client - wwwroot - MyFiles - FileA.cs - FileB.xml - Shared
当前尝试的路径代码
var filepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../../../MyFiles", "FileB.xml");
问题原因
- 相对路径基准错误:直接使用
"FileB.xml"时,程序的工作目录是Server项目的bin/debug/net7.0(exe运行目录),而非FileA所在的Client/MyFiles,因此找不到文件。 - 硬编码上级路径不可靠:
../../../../这种写法完全依赖编译后的目录层级,一旦项目部署位置、编译输出结构变更,路径就会失效,稳定性极差。
解决方法
方法1:利用输出目录复制(推荐)
既然FileB.xml已经被复制到Server/bin/debug/net7.0/MyFiles,直接从程序运行目录的子文件夹加载即可:
var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MyFiles", "FileB.xml"); Doc.Load(filePath);
确保FileB.xml的属性设置正确:选中文件→属性→复制到输出目录设为「始终复制」或「如果较新则复制」,生成操作设为「内容」。
方法2:直接读取项目源文件(仅开发阶段)
如果需要读取Client项目中的原始FileB.xml,可通过解决方案根目录拼接路径,但不建议用于生产环境:
// 获取解决方案根目录 var solutionRoot = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../../../../")); var filePath = Path.Combine(solutionRoot, "Client", "MyFiles", "FileB.xml"); Doc.Load(filePath);
内容的提问来源于stack exchange,提问作者st27
相关产品推荐
相关产品推荐

