92 lines
1.7 KiB
C#
92 lines
1.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.IO;
|
|
|
|
namespace DotnetStandardStreams
|
|
{
|
|
|
|
// THE GOAL:
|
|
// READ will return NULL when you read after the last line. This is fine.
|
|
// EOF will return TRUE when you read the last line.
|
|
// We want EOF to return FALSE after you read the last line and TRUE when you read AFTER the last line.
|
|
public class FileTextSource : ITextSource
|
|
{
|
|
protected FileStream? file;
|
|
protected StreamReader? reader;
|
|
protected string filename;
|
|
protected string? lastLineRead = string.Empty; // Do NOT make this null at first.
|
|
|
|
public FileTextSource(string filename)
|
|
{
|
|
this.filename = filename;
|
|
file = null;
|
|
reader = null;
|
|
}
|
|
|
|
public virtual void Open()
|
|
{
|
|
file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
|
|
reader = new StreamReader(file);
|
|
}
|
|
|
|
public virtual IEnumerable<string> ReadAll()
|
|
{
|
|
string line = Read();
|
|
|
|
while (!Eof())
|
|
{
|
|
yield return line;
|
|
|
|
line = Read();
|
|
}
|
|
}
|
|
|
|
public virtual string Read()
|
|
{
|
|
if (!Eof())
|
|
{
|
|
string? result = reader?.ReadLine();
|
|
lastLineRead = result;
|
|
|
|
return result ?? string.Empty;
|
|
}
|
|
else
|
|
return string.Empty;
|
|
}
|
|
|
|
public virtual bool Eof()
|
|
{
|
|
//return reader?.EndOfStream ?? true;
|
|
return lastLineRead == null;
|
|
}
|
|
|
|
public virtual void Close()
|
|
{
|
|
try
|
|
{
|
|
// TODO: Uh... why are we calling Flush() on a file-read operation?
|
|
file?.Flush();
|
|
}
|
|
finally
|
|
{
|
|
try
|
|
{
|
|
file?.Close();
|
|
}
|
|
finally
|
|
{
|
|
file?.Dispose();
|
|
}
|
|
}
|
|
}
|
|
|
|
public void ReadAll(Action<string> readAction)
|
|
{
|
|
foreach (string line in ReadAll())
|
|
readAction(line);
|
|
}
|
|
}
|
|
} |