新手尝试在Visual Studio 2022中读取CSV文件。我可以从我自己的桌面上读取这个文件,但是当我试图在下面的文件夹中访问它时,我得到了一个非法的路径字符。有人能告诉我正确的访问路径吗?
屏幕截图和代码如下:
namespace ReadDataFromCSV{
internal class Program
{
static void Main(string[] args)
{
string filePath = System.IO.File.ReadAllText(@"C:\Users\kirst\source\repos\ReadDataFromCSV\ReadDataFromCSV\CSV_files\TestCountries.csv");
// string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"CSV_files\TestCountries.csv");
// string[] files = File.ReadAllLines(filePath);
{
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();
}
}
}
}
谢谢你,谢谢
Kirsty
1条答案
按热度按时间dauxcl2d1#
filePath
变量初始化时会将文件的全部内容分配给它,而不仅仅是路径,因此当使用它打开StreamReader
时,您会得到意想不到的结果。要解决这个问题,请更改它从这里创建的行:
对此:
这似乎也是练习/学习代码,所以我不会太深入地研究具体的方法,但我会说我个人倾向于使用
File.ReadLines()
(不是File.ReadAllLines()
)来代替这里的StreamReader
。我也倾向于使用内置的TextFieldParser
或NuGet的专用CSV库。我不想使用string.Split()
之类的东西来处理CSV数据。