CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Dec 2008
    Posts
    9

    Question 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.

  2. #2
    Join Date
    Jul 2006
    Posts
    297

    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.

  3. #3
    Join Date
    Nov 2007
    Location
    .NET 3.5 / VS2008 Developer
    Posts
    624

    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();

  4. #4
    Join Date
    Jul 2006
    Posts
    297

    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
  •  





Click Here to Expand Forum to Full Width

Featured