使用 StreamReader 时如何指定从文件中开始读取的位置?
使用 StreamReader 时如何指定从文件中开始读取的位置?
我创建了一个流读取器对象以及一个文件流对象。 创建两个对象后,我将如何继续控制 StreamReader 从文件开始读取的位置?
假设文件的内容如下,
// song list.
// junk info.
1. Song Name
2. Song Name
3. Song Name
4. Song Name
5. Song Name
6. Song Name
我如何控制流读取器从#2 读取? 另外,我怎样才能控制在哪里通过类似的分隔符(如#5)停止读取?
编辑:我所说的分隔符是指一种让 StreamReader 从 ('2.') 开始读取的方法
How do you specify where to start reading in a file when using StreamReader?
I have created a streamreader object, along with a file stream object. After both objects are created, how would I go upon controlling where I want the StreamReader to start reading from a file?
Let's say the file's contents are as follows,
// song list.
// junk info.
1. Song Name
2. Song Name
3. Song Name
4. Song Name
5. Song Name
6. Song Name
How would I control the streamreader to read from let's say #2? Also, how could I also control where to make it stop reading by a similar delimiter like at #5?
Edit: By delimiter I mean, a way to make StreamReader start reading from ('2.')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否尝试将文件反序列化为内存中的对象? 如果是这样,您可能只想使用 ReadLine 或类似的方法解析整个文件,存储每一行,然后通过数据结构(例如 KeyValuePair)访问它。 。
更新:好的...有了新信息,我认为您有两个选择。 如果您正在阅读直到找到匹配项,则可以
Peek()
,检查该字符是否是您要查找的字符,然后Read()< /代码>。 或者,如果您正在寻找设定的位置,您可以简单地
Read()
那么多字符并丢弃返回值。如果您正在寻找复杂的分隔符,您可以将整行甚至整个文件读入内存并使用 正则表达式。
希望有帮助...
Are you trying to deserialize a file into some in-memory object? If so, you may want to simply parse the entire file in using
ReadLine
or something similar, store each line, and then access it via a data structure such as aKeyValuePair<int, string>
.Update: Ok... With the new info, I think you have two options. If you're looking at reading until you find a match, you can
Peek()
, check to see if the character is the one you're looking for, and thenRead()
. Alternatively, if you're looking for a set position, you can simplyRead()
that many characters and throw away the return value.If you're looking for complex delimiter, you can read the entire line or even the entire file into memory and use Regular Expressions.
Hope that helps...
如果文件包含新行分隔符,您可以使用 ReadLine< /a> 一次读取一行。
因此,要从第 2 行开始读取,您将读取第一行并丢弃,然后读取直到第 5 行。
If the file contains new line delimiters you can use ReadLine to read a line at a time.
So to start reading at line #2, you would read the first line and discard and then read lines until line #5.
如果内容只是这样的纯文本,您应该使用 StreamReader 的 ReadLine 方法。
http://msdn.microsoft.com/en- us/library/system.io.streamreader.readline.aspx
-Oisin
Well if the content is just plain text like that, you should use the StreamReader's ReadLine method.
http://msdn.microsoft.com/en-us/library/system.io.streamreader.readline.aspx
-Oisin