将 .txt 文件读入列表 C#

JD2*_*775 0 c# list

我是来自 Python 的 C# 新手,这篇文章对我来说真的很困惑......

我有一个简单的 .txt 文件,其中包含以下值:

Name1
Name2
Name3
Run Code Online (Sandbox Code Playgroud)

我想将它们读入一个列表,每行列表中有 1 个项目。看起来很容易,但我无法弄清楚。我做错了什么?谢谢

using System;
using System.Collections.Generic;

string LOG_PATH = "C:\\Users\\xyz\\source\\repos\\LoopPractice\\TextFile1.txt"
List<string> allLinesText = ReadAllLines(LOG_PATH).ToList();
Run Code Online (Sandbox Code Playgroud)

Mik*_*keH 5

我想,也许你找到了文档,ReadAllLines但没有包含完整的声明。

尝试这个:

List<string> allLinesText = System.IO.File.ReadAllLines(LOG_PATH).ToList();
Run Code Online (Sandbox Code Playgroud)

ReadAllLinesstatic类中的一个方法System.IO.File。如果你想简化上面的行,你可以添加using System.IO;到文件的顶部,那么你的代码将变成:

List<string> allLinesText = File.ReadAllLines(LOG_PATH).ToList();
Run Code Online (Sandbox Code Playgroud)