In C# Cake How to Read a Text File into List<string>?

216 Views Asked by At

Given a carriage return delimited text file say of folder names, how do I read this file into List in the Cake build system for C#?

When I try to use the File class, it complains that File(string) is a method, which is not valid given the context:

filePath filePath;
string fileContents = File.ReadAllText(filePath FullPath);

How would I write this so it works with Cake?

https://cakebuild.net/

2

There are 2 best solutions below

0
C. Augusto Proiete On BEST ANSWER

Cake has its own File class, so there's a namespace conflict where the compiler doesn't know which File class you want to use.

You have to fully-qualify the type name in your call, to include the System.IO namespace:

filePath filePath;
string fileContents = System.IO.File.ReadAllText(filePath FullPath);

You might also be interested in the Cake.FileHelpers addin which adds a set of aliases for Cake to help with simple file operations such as Reading, Writing and Replacing text.

3
Joel Coehoorn On

You want File.ReadAllLines() or File.ReadLines().

Neither of these returns a List<string>, but both create objects that work with foreach loops and Linq extensions, including .ToList() if you need it.

I also see this:

When I try to use the File class, it complains that File(string) is a method, which is not valid given the context:

There are two possibilities here. One is, in addition to System.IO.File, you either have another File type or a File method in the same scope. If this is the issue, then remove any using System.IO directive you may have at the top of the code file and fully-qualify any use of System.IO.File.

The second possibility relates to the code snippet, with the repeating filePath filePath or filePath fullPath on both lines. Neither really makes sense at all, and indicates there might be a lack of understanding for basic syntax.