只读指定的范围

时间:2011-03-31 14:02:59

标签: c# .net wpf stream

我有一个文本文件,我只想从中读取指定的范围(如位置20到80)。

我正在使用以下代码,但它从0读取到跨度的长度。

char[] buffer = new char[span.Length];
using (StreamReader reader = new StreamReader(filename))
{               
    reader.ReadBlock(buffer, 0, span.Length);
}

有人能帮助我吗?感谢

3 个答案:

答案 0 :(得分:2)

char[] buffer = new char[span.Length];
using (StreamReader reader = new StreamReader(filename))
{    
    reader.BaseStream.Seek(span.Start, SeekOrigin.Begin); // or SeekOrigin.Current if you want to loop
    reader.Read(buffer, 0, span.Length);
}

假设span的类型具有Start属性。

答案 1 :(得分:0)

char[] buffer = new char[span.Length];
using (StreamReader reader = new StreamReader(filename))
{               
    reader.ReadBlock(buffer, startIndex, span.Length);
}

startIndex =从哪里开始
span.Length =要读取的字符数

答案 2 :(得分:-1)

你试过吗?

char[] buffer = new char[span.Length];
using (StreamReader reader = new StreamReader(filename))
{               
    reader.ReadBlock(buffer, 20, span.Length);
}