0

I want to have file content displayed in console. I've managed something like this:

using (var file = new FileStream(fileLocation, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (StreamReader sr = new StreamReader(file))
{
    while(true)
    {
        var line = sr.ReadLine();

        if (line != null)
            Console.WriteLine(line);
    }
}

I dont like this because instead of waiting for new content to appear, it is iterating over and over in while loop. Is there any better way to do that?

dafie
  • 951
  • 7
  • 25

1 Answers1

1

Probably check if the file reading is not over yet saying while(sr.ReadLine() != null){

string line = string.Empty;
while((line = sr.ReadLine()) != null)
{
   Console.WriteLine(line);
}

Per your comment looks like you wanted to monitor a specific file and keep writing it's content to Console. In that case, you should consider using FileSystemWatcher in System.IO namespace. An simple example would be:

public static Watch() 
{
    var watch = new FileSystemWatcher();
    watch.Path = fileLocation;
    watch.Filter = "*.txt";  // Only text files
    watch.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite; 
    watch.Changed += new FileSystemEventHandler(OnChanged);
    watch.EnableRaisingEvents = true;
}

private static void OnChanged(object source, FileSystemEventArgs e)
{
   // Do some processing
}

You can see this existing post c# continuously read file

Rahul
  • 76,197
  • 13
  • 71
  • 125
  • I don't want to stop if file reading is over. I want to display real time file content (which is changing all time) in console. – dafie May 12 '20 at 20:33
  • 1
    @dafie then your question is not clear enough. Edit your question and mention the same. – Rahul May 12 '20 at 20:35
  • I think stream reader is necessary to get only new content from file. Your example does not provide that. – dafie May 13 '20 at 11:59
  • @dafie I shown an abstract example to let you familiar with the approach and not a solid testable solution. You can research more on that as well look into the linked question for other approaches as well. – Rahul May 13 '20 at 12:17