JD2775
JD2775

Reputation: 3801

Reading .txt file into a List C#

I am new to C# coming from Python, and this piece is really confusing to me...

I have a simple .txt file with the values:

Name1
Name2
Name3

I want to read those into a List, 1 item in list per row. Seems easy enough but I can't figure it out. What am I doing incorrectly? Thanks

using System;
using System.Collections.Generic;

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

Upvotes: 0

Views: 281

Answers (1)

MikeH
MikeH

Reputation: 4395

I think, perhaps, you found the documentation to ReadAllLines but didn't include the full declaration.

Try this:

List<string> allLinesText = System.IO.File.ReadAllLines(LOG_PATH).ToList();

ReadAllLines is a static method in the class System.IO.File. If you want to simplify the above line you could add using System.IO; to the top of your file, then your code would become:

List<string> allLinesText = File.ReadAllLines(LOG_PATH).ToList();

Upvotes: 6

Related Questions