72 lines
1.2 KiB
C#
72 lines
1.2 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.IO;
|
|
|
|
namespace DotnetStreams
|
|
{
|
|
public class FileTextSource : ITextSource
|
|
{
|
|
protected FileStream? file;
|
|
protected StreamReader? reader;
|
|
protected string filename;
|
|
|
|
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 = reader?.ReadLine();
|
|
while (line != null)
|
|
{
|
|
yield return line;
|
|
line = reader?.ReadLine();
|
|
}
|
|
}
|
|
|
|
public virtual string Read()
|
|
{
|
|
if (!Eof())
|
|
return reader?.ReadLine() ?? string.Empty;
|
|
else
|
|
return string.Empty;
|
|
}
|
|
|
|
public virtual bool Eof()
|
|
{
|
|
return reader?.EndOfStream ?? true;
|
|
}
|
|
|
|
public virtual void Close()
|
|
{
|
|
try
|
|
{
|
|
file?.Flush();
|
|
}
|
|
finally
|
|
{
|
|
try
|
|
{
|
|
file?.Close();
|
|
}
|
|
finally
|
|
{
|
|
file?.Dispose();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|