asp. net下使用foreach简化文本文件的访问。

仅有尝试过,努力过,坚持过,才能有收获。一分耕耘,一分收获,仅有努力了,才能绽放出成功的花朵。只要功夫深,铁杵磨成针。我相信,只要我朝着这个梦想努力奋斗,坚持不懈,那么,我就必须会成功!

很多时候,我们总是按照行的方式访问文本文件,使用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下使用foreach简化文本文件的访问。。踏出一步又一步,又只能收回一步一步。成长,有些苦涩始终都要去尝。更多关于asp. net下使用foreach简化文本文件的访问。请关注haodaima.com其它相关文章!

标签: 文本文件 asp