Resolved Select with a window and Read last line

Steve90

New member
Joined
May 5, 2020
Messages
4
Programming Experience
Beginner
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


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();
            }
        }
    }
}
 
Last edited by a moderator:
Note that there is no ReadLinesAsync method. If you wanted to do it async then you could write your own method:
C#:
private async Task<string> GetLastLine(string filePath)
{
    using (var reader = new StreamReader(filePath))
    {
        string line = null;

        while (!reader.EndOfStream)
        {
            line = await reader.ReadLineAsync();
        }

        return line;
    }
}
 
If you want just the last line then read all the lines and discard all but the last one:
C#:
var lastLine = File.ReadLines(filePath).Last();
Do you mean something like this?
C#:
private void OpenFileBtn_ClickAsync(object sender, EventArgs e)
{
    using(OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text File|*.txt", Multiselect = false })
    {
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            var lastLine = File.ReadLines(ofd.FileName).Last();
        }
    }
}
I tried it, but it don't work
 
Firstly, I already formatted your code for you in post #1 and sent a notification not to post unformatted code and you did it again. I have now formatted your code again. Please do not post unformatted code as it is too hard to read.

Secondly, "it don't work" is NEVER an adequate explanation of a problem. You ALWAYS need to EXPLAIN what you expect to happen and what actually does happen. Did you bother to read that code and think about what it does? What I posted was just an example, i.e. something to demonstrate a principle. It's up to you to implement that principle. In your original code you displayed the text of the file in a RuchTextBox. Were you expecting that latest code to do something similar, despite not referring to that RichTextBox anywhere?
 
Note that there is no ReadLinesAsync method. If you wanted to do it async then you could write your own method:
But there is a ReadAllLinesAsync(). :)

Unfortunately, it returns a Task<string[]>, so it'll be a waste of memory to read all the lines into memory and only to take the last line. So the roll-your-own solution proposed in post #3 is still the best approach if you must run async.
 
But there is a ReadAllLinesAsync(). :)

Unfortunately, it returns a Task<string[]>, so it'll be a waste of memory to read all the lines into memory and only to take the last line. So the roll-your-own solution proposed in post #3 is still the best approach if you must run async.
That method is also .NET Core only. We don't know whether this question relates to .NET Framework or .NET Core but I'd tend to guess .NET Framework for beginners still.
 
@Steve90 - Please refer to the documentation for the examples you have been shown.

How does this :
private async Task<string> GetLastLine(string filePath)
Look like this :
private void OpenFileBtn_ClickAsync(object sender, EventArgs e)

Don't just take code from any website and expect it to do what you want off the bat. You should first know what the code does before you use it. Read about async keyword : async - C# Reference and Last() : Enumerable.Last Method (System.Linq) and read How to: Return a Value from a Task to get an understanding of why and how it works. You may also want to read up on Task too. The docs exist for a reason, and I suggest searching through MSDN so you get an understanding of the code you are trying to work with. Don't be a copy/paste programmer.

This is often why I prefer to explain what my code examples do, rather than providing code without explanatory inline comments (No matter how simple and trivial the example may be). The above replies are a prime example of why I do... That's not a dig at you John. -- Our OP really should be researching what you gave them and first compare it to the code they already have, and that includes all of the entwined code in your method example too, and try to understand it by reading the abundance of available documentation before coming back to the forums.

I'm not trying to discourage questioning @Steve90, as that is what this board is for. This forum also thrives on teaching people how to become better programmers. But not everyone has the time to write out a step by step example of the code they provide you with. Most examples are no intended to be taken as they are, and often require you to edit them and study them yourself. It is expected by us that you do your own research into the example you were provided with and if there is something you still don't understand afterwards, you can then come back and ask us.

For the most part, you should spend some time studying the courteous example you received and try to understand how and why it works as it does. Use the debugger, and alter the code to your liking. And only when you've spent some time changing and attempting to implement the example @jmcilhinney gave you. Show us what you changed, when you understand what you need to change.
 
Back
Top Bottom