很多时候,我们总是按照行的方式访问文本文件,使用foreach语句能够极大地简化访问逻辑:例如:
foreach(stringlineinnewLineReader(”c:abc.txt”))
Console.WriteLine(line);
完整代码如下:
usingSystem;
usingSystem.IO;
usingSystem.Text;
usingSystem.Collections;
namespaceForks.Utils.IO
{
publicstructLineReader:IDisposable
{
publicLineReader(stringfile,Encodingencoding):this(file,encoding,false)
{
}
publicLineReader(stringfile,Encodingencoding,boolignoreBlankLines):this(newFileStream(file,FileMode.Open,FileAccess.Read,FileShare.Read),encoding,ignoreBlankLines)
{
}
publicLineReader(Streamstream,Encodingencoding):this(stream,encoding,false)
{
}
publicLineReader(Streamstream,Encodingencoding,boolignoreBlankLines):this(newStreamReader(stream,encoding),ignoreBlankLines)
{
}
publicLineReader(TextReaderreader):this(reader,false)
{
}
TextReadermReader;
boolmIgnoreBlankLines;
publicLineReader(TextReaderreader,boolignoreBlankLines)
{
mReader=reader;
mIgnoreBlankLines=ignoreBlankLines;
mCurrent=null;
}
publicLineReaderGetEnumerator()
{
returnthis;
}
publicvoidReset()
{
thrownewNotSupportedException("LineReaderÖ»ÄܶÁÈ¡Ò»´Î");
}
stringmCurrent;
publicstringCurrent
{
get
{
returnmCurrent;
}
}
publicboolMoveNext()
{
do
{
mCurrent=mReader.ReadLine();
}while(mIgnoreBlankLines&&mCurrent!=null&&mCurrent.Length==0);
returnmCurrent!=null;
}
publicvoidDispose()
{
mReader.Close();
}
}
}
测试代码:
usingSystem;
usingSystem.IO;
usingSystem.Text;
usingNUnit.Framework;
usingForks.Test;
namespaceForks.Utils.IO
{
[TestFixture]
publicclassLineReaderTest
{
conststringTestLines=@"abcasdewrafae
startwithblanks
endwithblanks
ºº×Öabc123!@#
endoftext!";
[Test]
publicvoidReadFromReader()
{
doTest(newLineReader(newStringReader(TestLines)));
}
[Test]
publicvoidReadFromFile()
{
stringfile=Path.GetTempFileName();
try
{
StringUtil.SaveToFile(TestLines,file,Encoding.GetEncoding("gb2312"));
doTest(newLineReader(file,Encoding.GetEncoding("gb2312")));
}
finally
{
FileUtil.SafeDelete(file);
}
}
[Test]
publicvoidReadFromStream()
{
stringfile=Path.GetTempFileName();
try
{
StringUtil.SaveToFile(TestLines,file,Encoding.GetEncoding("gb2312"));
using(Streamstream=newFileStream(file,FileMode.Open))
doTest(newLineReader(stream,Encoding.GetEncoding("gb2312")));
}
finally
{
FileUtil.SafeDelete(file);
}
}
voiddoTest(LineReaderreader)
{
StringBuildersb=newStringBuilder();
foreach(stringlineinreader)
sb.Append(line+Environment.NewLine);
Assert.AreEqual(TestLines+Environment.NewLine,sb.ToString());
}
[Test]
publicvoidIgnoreBlankLine()
{
foreach(stringlineinnewLineReader(newStringReader(TestLines),true))
Assert.IsTrue(line.Length!=0);
}
}
}