C# - 读取当前项目内文件夹中的 CSV 文件

问题描述 投票:0回答:1

新手尝试在 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();
        }
    }
}

}

谢谢!

科斯蒂

c# csv visual-studio-2022 opencsv read.csv
1个回答
0
投票

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";
© www.soinside.com 2019 - 2024. All rights reserved.