C#读取项目内CSV文件报错:路径含非法字符,求正确路径
解决“路径包含非法字符”错误的方案
核心问题分析
你原代码里的第一行存在逻辑错误:
string filePath = System.IO.File.ReadAllText(@"C:\Users\kirst\source\repos\ReadDataFromCSV\ReadDataFromCSV\CSV_files\TestCountries.csv");
这行代码是把文件内容读取后赋值给filePath变量,而非存储文件路径。后续StreamReader接收的是文件内容字符串(而非合法路径),直接触发了“路径包含非法字符”错误。
正确实现方式
方式1:使用绝对路径(仅测试场景用)
修正路径赋值逻辑,确保filePath存储的是路径字符串:
using System; using System.IO; namespace ReadDataFromCSV { internal class Program { static void Main(string[] args) { // 正确存储文件路径 string filePath = @"C:\Users\kirst\source\repos\ReadDataFromCSV\ReadDataFromCSV\CSV_files\TestCountries.csv"; try { using (StreamReader reader = new StreamReader(filePath)) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadKey(); } } }
方式2:使用相对路径(推荐,适配项目部署)
这种方式无需硬编码绝对路径,更灵活,但需先设置文件属性:
- 在Visual Studio解决方案资源管理器中,找到
CSV_files\TestCountries.csv文件 - 右键选择“属性”,将复制到输出目录设置为“如果较新则复制”或“始终复制”
修正后的代码:
using System; using System.IO; namespace ReadDataFromCSV { internal class Program { static void Main(string[] args) { // 组合项目输出目录与相对路径 string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"CSV_files\TestCountries.csv"); try { using (StreamReader reader = new StreamReader(filePath)) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadKey(); } } }
也可以用你注释掉的程序集路径方式,需引用System.Reflection:
using System; using System.IO; using System.Reflection; namespace ReadDataFromCSV { internal class Program { static void Main(string[] args) { string assemblyDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string filePath = Path.Combine(assemblyDir, @"CSV_files\TestCountries.csv"); try { using (StreamReader reader = new StreamReader(filePath)) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadKey(); } } }
补充说明
- 确认
CSV_files文件夹存在于项目目录中,且TestCountries.csv路径拼写无错误 - 使用相对路径时,必须设置文件的“复制到输出目录”属性,否则编译后文件不会被复制到输出文件夹,会出现文件找不到的错误
内容的提问来源于stack exchange,提问作者Kirsty Meredith
相关产品推荐
相关产品推荐

