asp. net下使用foreach简化文本文件的访问。
asp. net下使用foreach简化文本文件的访问。
发布时间:2016-12-29 来源:查字典编辑
摘要:很多时候,我们总是按照行的方式访问文本文件,使用foreach语句能够极大地简化访问逻辑:例如:foreach(stringlineinne...

很多时候,我们总是按照行的方式访问文本文件,使用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);

}

}

}

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新asp.net教程学习
热门asp.net教程学习
编程开发子分类