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

puruo6ea  于 12个月前  发布在  C#
关注(0)|答案(1)|浏览(100)

新手尝试在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

dauxcl2d

dauxcl2d1#

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";

这似乎也是练习/学习代码,所以我不会太深入地研究具体的方法,但我会说我个人倾向于使用File.ReadLines()不是File.ReadAllLines())来代替这里的StreamReader。我也倾向于使用内置的TextFieldParser或NuGet的专用CSV库。我不想使用string.Split()之类的东西来处理CSV数据。

相关问题