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ö»äü¶áè¡ò»´î");
}
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();
}
}
}
测试代码:
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);
}
}
}
您可能感兴趣的文章:
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!
网友评论