Use foreach in ASP. NET to simplify access to text files.
Last Update:2018-12-08
Source: Internet
Author: User
In many cases, we always access text files in line mode. Using the foreach statement can greatly simplify the access logic: for example:
Foreach (string line in new linereader ("C: \ abc.txt "))
Console. writeline (line );
Complete Code As follows:
Using system;
Using system. IO;
Using system. text;
Using system. collections;
Namespace forks. utils. Io
{
Public struct linereader: idisposable
{
Public linereader (string file, encoding): This (file, encoding, false)
{
}
Public linereader (string file, encoding, bool ignoreblanklines): This (New filestream (file, filemode. Open, fileaccess. Read, fileshare. Read), encoding, ignoreblanklines)
{
}
Public linereader (Stream stream, encoding): This (stream, encoding, false)
{
}
Public linereader (Stream stream, encoding, bool ignoreblklines): This (New streamreader (stream, encoding), ignoreblklines)
{
}
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 ");
}
String mcurrent;
Public String current
{
Get
{
Return mcurrent;
}
}
Public bool movenext ()
{
Do
{
Mcurrent = mreader. Readline ();
} While (mignoreblanklines & mcurrent! = NULL & mcurrent. Length = 0 );
Return mcurrent! = NULL;
}
Public void dispose ()
{
Mreader. Close ();
}
}
}
Test code:
Using system;
Using system. IO;
Using system. text;
Using nunit. Framework;
Using forks. test;
Namespace forks. utils. Io
{
[Testfixture]
Public class linereadertest
{
Const string testlines = @ "ABC ASD EWR AFA E
Start with blanks
End with blanks
° ×Öabc123! @#
End of text! ";
[Test]
Public void readfromreader ()
{
Dotest (New linereader (New stringreader (testlines )));
}
[Test]
Public void readfromfile ()
{
String file = path. gettempfilename ();
Try
{
Stringutil. savetofile (testlines, file, encoding. getencoding ("gb2312 "));
Dotest (New linereader (file, encoding. getencoding ("gb2312 ")));
}
Finally
{
Fileutil. safedelete (File );
}
}
[Test]
Public void readfromstream ()
{
String file = path. gettempfilename ();
Try
{
Stringutil. savetofile (testlines, file, encoding. getencoding ("gb2312 "));
Using (Stream stream = new filestream (file, filemode. Open ))
Dotest (New linereader (stream, encoding. getencoding ("gb2312 ")));
}
Finally
{
Fileutil. safedelete (File );
}
}
Void dotest (linereader reader)
{
Stringbuilder sb = new stringbuilder ();
Foreach (string line in Reader)
SB. append (LINE + environment. newline );
Assert. areequal (testlines + environment. newline, SB. tostring ());
}
[Test]
Public void ignoreblankline ()
{
Foreach (string line in new linereader (New stringreader (testlines), true ))
Assert. istrue (line. length! = 0 );
}
}
}