StreamReader获取并设置位置 [英] StreamReader get and set position
问题描述
我只是想读取一个大型CSV文件并将Stream位置保存在列表中.之后,我必须从列表中读取位置,并将Streamreader的位置设置为该char并读取一行! 但是在我读完第一行并用
i simply want to read a large CSV-File and save the Stream position in a list. After that i have to read the position from the list and set the position of the Streamreader to that char and read a line!! But after i read the first line and return the streamposition with
StreamReader r = new StreamReader("test.csv");
r.readLine();
Console.WriteLine(r.BaseStream.Position);
我得到"177",这是文件中的所有字符! (这只是一个简短的示例文件) 我没有在这里找到能帮助我的东西!
i get "177", which are the total chars in the file! (it's only a short examplefile) i didn't found anything like that here arround which helped me!
为什么?
完整方法:
private void readfile(object filename2)
{
string filename = (string)filename2;
StreamReader r = new StreamReader(filename);
string _top = r.ReadLine();
top = new Eintrag(_top.Split(';')[0], _top.Split(';')[1], _top.Split(';')[2]);
int siteindex = 0, index = 0;
string line;
sitepos.Add(r.BaseStream.Position); //sitepos is the a List<int>
while(true)
{
line = r.ReadLine();
index++;
if(!string.IsNullOrEmpty(line))
{
if (index > seitenlaenge)
{
siteindex++;
index = 1;
sitepos.Add(r.BaseStream.Position);
Console.WriteLine(line);
Console.WriteLine(r.BaseStream.Position.ToString());
}
}
else break;
maxsites = siteindex;
}
reading = false;
}
文件如下:
name;age;city
Simon;20;Stuttgart
Daniel;34;Ostfildern
以此类推 这是一个程序练习: http://clean-code-advisors.com/ressourcen/application-katas (Katas CSV查看器)我目前处于3级文化水平
And so on it's a Program exercise: http://clean-code-advisors.com/ressourcen/application-katas (Katas CSV viewer) I'm currently at literation 3
推荐答案
StreamReader
使用的是缓冲流,因此StreamReader.BaseStream.Position
可能会比使用ReadLine
实际读取"的字节数提前
StreamReader
is using a buffered stream, and so StreamReader.BaseStream.Position
will likely be ahead of the number of bytes you have actually 'read' using ReadLine
.
在 查看全文