|
-
September 7th, 2009, 05:59 AM
#1
Writing specific lines to an ArrayList
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.
-
September 7th, 2009, 11:41 AM
#2
Re: Writing specific lines to an ArrayList
Keep a buffer of the previous 6 lines. When you read the error line copy those 6 lines into the arraylist.
-
September 8th, 2009, 07:20 AM
#3
Re: Writing specific lines to an ArrayList
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.
Code:
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();
-
September 9th, 2009, 10:09 AM
#4
Re: Writing specific lines to an ArrayList
Even if you do need an array you can always do
Code:
List<Int32> ids = new List<Int32>();
// add stuff here
Int32[] idArray = ids.ToArray();
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|