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

    Read last line of a text file

    Anyone have any idea how to make a StreamReader read the last line of a text file without knowing what it is. For example if I have a text file like this:

    Code:
    1
    2
    3
    4
    5
    6
    7
    how can I make my program read the last line which is "7" but with out me telling the program that it is seven? Any help is appreciated thanks

  2. #2
    Join Date
    Jun 2002
    Location
    Sweden
    Posts
    467

    Resolved Re: Read last line of a text file

    Maybe something like this:

    int index = 1;
    stream.Seek(0, SeekOrigin.End)
    while(stream.ReadByte () != '\n')
    {
    stream.Seek(index, SeekOrigin.End)
    ++index
    }
    "The making of software, like the making of sausages, should never be watched."

    http://blog.gauffin.org - .NET Coding/Architecture

  3. #3
    Join Date
    Mar 2008
    Location
    IRAN
    Posts
    811

    Wink Re: Read last line of a text file

    try this:

    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    
    namespace streamreader
    {
        class Program
        {
            static void Main(string[] args)
            {
                StreamReader st = new StreamReader("test.txt");
                string str = st.ReadToEnd();
                int x = str.LastIndexOf('\n');
                string lastline = str.Substring(x+1);
                Console.WriteLine(lastline);
                Console.ReadLine();
            }
        }
    }
    Touraj Ebrahimi [toraj_e] [at] [yahoo] [dot] [com]

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