很多时候,我们总是按照行的方式访问文本文件,使用foreach语句能够极大地简化访问逻辑:例如:
foreach (string line in new LineReader(”c:/abc.txt”))
Console.WriteLine(line);
完整代码如下:
using System;
using System.IO;
using System.Text;
using System.Collections;
namespace Forks.Utils.IO
{
public struct LineReader : IDisposable
{
public LineReader(string file, Encoding encoding) : this(file, encoding, false)
{
}
public LineReader(string file, Encoding encoding, bool ignoreBlankLines) : this(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read), encoding, ignoreBlankLines)
{
}
public LineReader(Stream stream, Encoding encoding) : this(stream, encoding, false)
{
}
public LineReader(Stream stream, Encoding encoding, bool ignoreBlankLines) : this(new StreamReader(stream, encoding), ignoreBlankLines)
{
}
public LineReader(TextReader reader) : this(reader, false)
{
}
TextReader mReader;
bool mIgnoreBlankLines;
public LineReader(TextReader reader, bool ignoreBlankLines)
{
mReader = reader;
mIgnoreBlankLines = ignoreBlankLines;
mCurrent = null;
}
public LineReader GetEnumerator()
{
return this;
}
public void Reset()
{
throw new NotSupportedException("LineReaderÖ»ÄܶÁÈ¡Ò»´Î");
}