Look at your code, please.
That looks like it was thrown together without any thought about what you are trying to do!
Throw it away, and think about your task: Read a file, find all the lines which are above lines with an asterisk, and return them.
So let's take it from the top: You need to return more than one line - so the obvious thing to do is to return a collection of strings instead of a single string. Because although you can return them as a single string, it makes life a lot harder for the code that calls your method - it has to "break it back up again" in order to use the information.
Let's change that:
public static List<string> FindLineAboveAsterisks(TextReader reader)
Now, it returns a collection of strings so the outside world can work with it.
But ... why are you passing it a TextReader? That means each time you call it, the outside world has to do the work of creating, opening, passing, and closing the reader - which is silly. Pass the path instead, and let the method do what it wants with it:
public static List<string> FindLineAboveAsterisks(string filePath)
Now, the caller looks easier to work with.
Let's start filling in the method: We need a List to return, and to process every line in a file. If we want to use every line, then let's just get them all and let the system handle it! That's pretty easy:
public static List<string> FindLineAboveAsterisks(string filePath)
{
List<string> lines = new List<string>();
foreach (string line in File.ReadLines(filePath))
{
}
return lines;
}
Now, what do we have to do with the lines?
Simple; we need to collect all the lines where the next line contains three asterisks.
So we need to know what the last line was. Let's add that:
public static List<string> FindLineAboveAsterisks(string filePath)
{
List<string> lines = new List<string>();
string lastLine = "";
foreach (string line in File.ReadLines(filePath))
{
lastLine = line;
}
return lines;
}
We need to check if the current line contains "***". If it does, add the last one to the collection. That's easy too - a quick
if
test will do it:
public static List<string> FindLineAboveAsterisks(string filePath)
{
List<string> lines = new List<string>();
string lastLine = "";
foreach (string line in File.ReadLines(filePath))
{
if (line.Contains("***"))
{
lines.Add(lastLine);
}
lastLine = line;
}
return lines;
}
Hang on ... it's finished, isn't it?
All we have to do now is call it and test it:
string path = @"D:\Test Data\List of hats.txt";
foreach (string line in FindLineAboveAsterisks(path))
{
Console.WriteLine(line);
}
Oh look - it works!
All I did was think about the task and break it down into "manageable chunks", each of which was pretty obvious, and easy to do.
And very quickly, we have working code.
So stop jumping right in, and think first: five minutes of planning can save you hours of working!