我有一个文本文件,如果假设文本文件每行有94个字符,我想一次读取前12个字符,一次读取下5个字符,依此类推。如何在c#中读取这样的内容 其实我试过这个
StreamReader reader = File.OpenText(filePath);
string line;
bool endOfFile = false;
string[] strProcessedTokens = new string[1000];
int i = 0;
while (!reader.EndOfStream & !endOfFile)
{
line = reader.ReadLine()
.Select(m => new
{
firstGroup = m.Substring(0, 12),
secondGroup = m.Substring(12, 5),
lastGroup = m.Substring(89, 5)
});
requestProcessor.ProcessRequest(line);
strProcessedTokens[i++] = line;
}
答案 0 :(得分:1)
不确定子串中使用的数字,但不是这样的
var lines = File.ReadAllLines(<PathOfYourFile>)
.Select(m => new {
firstGroup = m.Substring(0, 12),
secondGroup = m.Substring(12, 5),
//etc.
lastGroup = m.Substring(89,5)
});
File.ReadAllLines可以用于“合理”的文件大小。
修改强> 使用您的代码,您可以
while (!reader.EndOfStream & !endOfFile)
{
line = reader.ReadLine();
var firstGroup = line.Substring(0,12);
var secondGroup = line.Substring(12, 5);
var lastGroup = line.Substring(89,5);
requestProcessor.ProcessRequest(line);
strProcessedTokens[i++] = line;
}