awaiting Task.Delay
makes this operation quite easy, in combination with File.ReadLines
:
public async Task SlowPrint(string fileName)
{
//TODO stuff to generate real file path and check if it exists
foreach(var line in File.ReadLines(fileName))
{
Console.WriteLine(line);
await Task.Delay(700);
}
}
A pre C# 5.0 solution is harder, but certainly possible. Just create a timer and read a new line whenever it fires:
public void SlowPrint(string FileName)
{
var iterator = File.ReadLines(FileName).GetEnumerator();
System.Threading.Timer timer = null;
timer = new System.Threading.Timer(o =>
{
if (iterator.MoveNext())
Console.WriteLine(iterator.Current);
else
{
iterator.Dispose();
timer.Dispose();
}
}, null, 700, Timeout.Infinite);
}