When you use foreach with a string, you do NOT get lines! Nor should you. After all, a string is a sequence of characters.
Specifically, foreach works by calling GetEnumerator() and when you call string.GetEnumerator() you get a CharEnumerator (ie a sequence of characters).
When you need to loop through lines (instead of characters) of a string, you can use a StringReader (not StreamReader).
But in this case you have a file. To loop through the lines of a file, do NOT use File.ReadAllText(), and do NOT use File.ReadAllLines(), as suggested elsewhere, at least as your first choice.
Instead, look at File.ReadLines() (no All), again — at least as your first choice. This saves you from needing to load the entire file into memory all at the same time.
Additionally, looking at the final sample, as a matter of style it's much better if the method accepts the file_name as an argument and returns the data as a result.
Put it all together and we end up with this:
public static IEnumerable<string> LoadFile(string file_Name)
{
return File.ReadLines(file_Name).
Where(line => line != string.Empty && !line.StartsWith("//") );
}
var file = LoadFile("medallion.txt");
Even better, we probably don't want to accept lines that are only white space or only have whitespace before the comment marker (while still preserving indentation that may be significant):
public static IEnumerable<string> LoadFile(string file_Name)
{
return File.ReadLines(file_Name).
Where(line => {
var trimmed = line.Trim();
return trimmed != string.Empty && !trimmed.StartsWith("//");
});
}
var file = LoadFile("medallion.txt");
But since you say you're a beginner, you may need it to look more like this:
public static List<string> LoadFile(string file_Name)
{
var result = new List<string>();
var lines = File.ReadLines(file_Name);
foreach(string line in lines)
{
if (line != string.Empty && !line.StartsWith("//") )
{
result.Add(line);
}
}
return result;
}
var file = LoadFile("medallion.txt");
Which is more code to be less efficient, but now the only advanced feature you need to know about is generic collections, which is still a concept typcially introduced to college CS students in the first or second year.
foreach (string line in File.ReadAllText(file_name))- A typo? Did you mean to useReadAllLinesinstead?foreachworks withIEnumerable<T>, andstringimplementsIEnumerable<char>, therefore you get achar.