Click to See Complete Forum and Search --> : Writing specific lines to an ArrayList


mistermuv
September 7th, 2009, 05:59 AM
Hi

I have text file which I want to read into an ArrayList. Typically this would be straightforward and no problem however, what I am looking at doing is a little more complicated.

I want to search for a string "End of Error" and once this is found, which will be on a line on its own, is to then read the previous 6 lines into the ArrayList. The lines which hold the data to the error itself.

How would you go about this?

Thanks in advance.

monalin
September 7th, 2009, 11:41 AM
Keep a buffer of the previous 6 lines. When you read the error line copy those 6 lines into the arraylist.

eclipsed4utoo
September 8th, 2009, 07:20 AM
nothing real fancy needed.

I used a List<string> instead of an ArrayList. If you are using .Net 2.0 or higher, don't use ArrayList unless you absolutely have to.


List<string> dataOfError = new List<string>();

using (TextReader reader = new StreamReader(@"C:\test\test.txt"))
{
// loops until the end of the file
while (reader.Peek() > 0)
{
// reads in current line
string line = reader.ReadLine();

// compares current line
if (string.Compare(line, "End of Error", true) == 0)
break;

// adds line to list
dataOfError.Add(line);
}
}

// loops through the last six elements in the list.
for (int i = dataOfError.Count - 6; i < dataOfError.Count; i++)
{
Console.WriteLine(dataOfError[i]);
}

Console.Read();

monalin
September 9th, 2009, 10:09 AM
Even if you do need an array you can always do


List<Int32> ids = new List<Int32>();
// add stuff here
Int32[] idArray = ids.ToArray();