dafie
dafie

Reputation: 1169

Mirror file content in console

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?

Upvotes: 0

Views: 176

Answers (1)

Rahul
Rahul

Reputation: 77926

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

Upvotes: 1

Related Questions