新手尝试在 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();
}
}
}
}
谢谢!
科斯蒂
filePath
变量保存文件的全部内容,而不是路径,因此当尝试使用它打开StreamReader
时,你会得到意想不到的结果。
要解决此问题,请更改从中创建它的行:
string filePath = System.IO.File.ReadAllText(@"C:\Users\kirst\source\repos\ReadDataFromCSV\ReadDataFromCSV\CSV_files\TestCountries.csv");
对此:
string filePath = @"C:\Users\kirst\source\repos\ReadDataFromCSV\ReadDataFromCSV\CSV_files\TestCountries.csv";