Click here to Skip to main content
15,878,959 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I need to select a file with a window and read last line of the selected file.
I tried and I created this code at moment that let me select a file and read it all, but I need now to read just last row of the selected file.. Any solution please? Thx

What I have tried:

C#
private async void OpenFileBtn_ClickAsync(object sender, EventArgs e)
{
 using(OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text File|*.txt", Multiselect = false })
  {
   if (ofd.ShowDialog() == DialogResult.OK)
    {
     using (StreamReader rd = new StreamReader(ofd.FileName))
     {
      ReaderRichTxtBox.Text = await rd.ReadToEndAsync();
     }
    }
  }
}
Posted
Updated 5-May-20 5:17am
v2

There are lots of ways to do it, one easy way is to read in each line of the file and you can continue to overwrite a variable and when the loop is done reading the file your variable will have the last line in it.

An example of how to read through the lines is here, How to read a text file one line at a time - C# Programming Guide | Microsoft Docs[^] , plus millions of other examples online.
 
Share this answer
 
Comments
Member 14786879 5-May-20 8:50am    
I don't need to read line by line, I just need to select the file and read last line.
I already searched online for a solution but didn't find it.
Do you know how to implement my code?
ZurdoDev 5-May-20 9:04am    
As I said, one way IS to read line by line. Another way is to read into an array and then grab the last item but you're still reading the whole file. See Solution 2.

There are millions of examples of how to read files in C# but there will not be one that is exact to what you are doing but it is easy to figure out.
You could try
C#
using (StreamReader rd = new StreamReader(ofd.FileName))
{
   string[] lines = rd.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
   ReaderRichTxtBox.Text = lines[lines.Length - 1];
}
 
Share this answer
 
v2
Comments
Member 14786879 5-May-20 9:02am    
It say that there are 2 error:
- Environment.NewLine -> This is not possibile to convert from 'string' to 'char'
- StringSplitOptions.RemoveEmptyEntries -> This is not possible to convert to 'char'
phil.o 5-May-20 9:09am    
And yet, Split(String, StringSplitOptions) is defined. edit: in .NET Core 3.1 ...
I modified the solution with a syntax compatible with .NET Framework.
phil.o 5-May-20 9:58am    
I think Maciej Los deserves the mark better than I do; his solution appears to be slightly more elegant than mine. If you could correct this, that would be great.
Maciej Los 5-May-20 9:43am    
5ed!
phil.o 5-May-20 9:56am    
Thanks as well :)
First of all, please read this: Read Last 150 lines from the large text file using C#[^]

Quote:
It is easy to see that is is impossible to read last N lines without reading all previous lines.


So, you have to read "lines" to the end to be able to get the last one.

Another way is to read "lines" via File.ReadAllLines() method:

C#
string[] lines = File.ReadAllLines("fullfilename.txt");
int cnt = lines.Length-1;
string lastline = lines[cnt];


Note: there's no async version.

For async file access, please read this: Using Async for File Access (C#) | Microsoft Docs[^]

[EDIT]
Additional info from comment.

Richard Deeming wrote:

Rather than reading the entire file into an array, I'd be inclined to use ReadLines and LastOrDefault. :)

C#
string lastLine = File.ReadLines("fullfilename.txt").LastOrDefault();


File.ReadLines Method (System.IO) | Microsoft Docs[^]
 
Share this answer
 
v3
Comments
phil.o 5-May-20 9:20am    
5'd.
Maciej Los 5-May-20 9:42am    
Thank you.
Richard Deeming 7-May-20 12:21pm    
Rather than reading the entire file into an array, I'd be inclined to use ReadLines and LastOrDefault. :)
string lastLine = File.ReadLines("fullfilename.txt").LastOrDefault();

File.ReadLines Method (System.IO) | Microsoft Docs[^]
Maciej Los 7-May-20 13:19pm    
Very interesting! I wasn't enough inquisitive ;)
Thank you, Richard!
See updated answer ;)
Quote:
Hi I need to select a file with a window and read last line of the selected file.

If file is small, just reading the file is an OK solution, if file is huge, memory footprint will be huge too, and this can be a problem.

There is another approach using low level file functions
Those functions allow you to know the file length, seek to position and read/write from the position.
Say that last line is within last 100 chars of end of file:
open file
get length
seek to length-100 from beginning
read from position

FileStream.Seek(Int64, SeekOrigin) Method (System.IO) | Microsoft Docs[^]
Sample code:
C#
using System;
using System.IO;

public class FSSeek
{
    public static void Main()
    {
        long offset;
        int nextByte;

        // alphabet.txt contains "abcdefghijklmnopqrstuvwxyz"
        using (FileStream fs = new FileStream(@"c:\temp\alphabet.txt", FileMode.Open, FileAccess.Read))
        {
            for (offset = 1; offset <= fs.Length; offset++)
            {
                fs.Seek(-offset, SeekOrigin.End);
                Console.Write(Convert.ToChar(fs.ReadByte()));
            }
            Console.WriteLine();

            fs.Seek(20, SeekOrigin.Begin);

            while ((nextByte = fs.ReadByte()) > 0)
            {
                Console.Write(Convert.ToChar(nextByte));
            }
            Console.WriteLine();
        }
    }
}
// This code example displays the following output:
//
// zyxwvutsrqponmlkjihgfedcba
// uvwxyz
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900