How about create a function to return a list of strings for one group, then maybe a class to hold the values?
public static List<string> ReadGroup(TextReader tr)
{
string line = tr.ReadLine();
List<string> lines = new List<string>();
while (line != null && line.Length > 0)
{
lines.Add(line);
}
// change this to line == null if you have groups with no lines
if (lines.Count == 0)
{
return null;
}
return lines;
}
Then you can access the lines by index in the list:
String line;
String path = "c:/sample.txt";
using (StreamReader sr = new StreamReader(path))
{
while ((List<string> lines = ReadGroup(sr)) != null)
{
// you might want to check for lines.Count >= 4 if you will
// have groups with fewer lines to provide a better error
//display the readed lines in the text box
disTextBox.AppendText(string.Format("{0}\t{1}\t{2}{3}",
lines[0], lines[2], lines[3], Environment.NewLine);
}
sr.Close();
}
I notice that your first one has an extra line with "po Bo 1255". You need to know what format your file is to doanything meaningful. If the last two lines of a group are city and country, you need to use the count of lines. With a class:
class LineGroup // name whatever the data contains
{
public string Name { get; set; }
public string Code { get; set; }
public string City { get; set; }
public string Country { get; set; }
public LineGroup(List<string> lines)
{
if (lines == null || lines.Count < 4)
{
throw new ApplicationException("LineGroup file format error: Each group must have at least 4 lines");
}
Name = lines[0];
Code = lines[1];
City = lines[lines.Count - 2];
Country = lines[lines.Count - 1];
}
}
And to process:
while ((List<string> lines = ReadGroup(sr) != null)
{
LineGroup group = new LineGroup(lines);
//display the readed lines in the text box
disTextBox.AppendText(string.Format("{0}\t{1}\t{2}{3}",
group.Name, group.City, group.Country, Environment.NewLine);
}