C# StreamReader 标记问题

3
我想要做的是记住输入流中的位置,并在以后回到那里。在Java中使用mark()和reset()非常简单,但我不知道如何在C#中实现。没有这样的方法。
例如:
public int peek() 
{
    try 
    {
        file.x; //in java file.mark(1)
        int tmp = file.read();
        file.+ //in java file.reset();
        return tmp;
    } 
    catch (IOException ex) {} 
    return 0;
}
2个回答

5

我不知道有没有这样的功能,但是您可以使用类似堆栈(Stack)的数据结构,通过Push()和Pop()方法来按顺序上下移动标记:

FileStream file = new FileStream(...);

try {
  Stack<long> markers = new Stack<long>();

  markers.Push(file.Position);

  file.Read(....);

  file.Seek(markers.Pop(),SeekOrigin.Begin);
} finally {
  file.Close();
}

基于字典的另一个想法:

FileStream file = new FileStream(...);

try {
  Dictionary<string,long> markers = new Dictionary<string,long>();

  markers.Add("thebeginning",file.Position);

  file.Read(....);

  file.Seek(markers["thebeginning"],SeekOrigin.Begin);
} finally {
  file.Close();
}

1
+1,很好的解决方案,但我猜你是指堆栈初始化在另一个范围内,例如类级别? ;) - Abel
不一定,这取决于您想在哪里使用它,在这里堆栈立即位于与文件 I/O 调用相同的作用域中。Stack<> 只是其中一种解决方案,您也可以使用 Dictionary<string,long> 并实际上给出 NAMED 标记,这都没问题 :) - Lloyd
+1,喜欢那个解决方案!还有一种可能:子类化FileStream并将该堆栈添加到该类中。 - Sascha
谢谢,我会尝试并发布结果。 - Strausa

0
如果您使用的是StreamReader,请记住它并不完全是一个Stream,但您可以访问其BaseStream属性:
StreamReader reader = new StreamReader("test.txt");
Stream stream = reader.BaseStream;

它将会给出你在流中当前的位置:

long pos = stream.Position;

它将允许您返回那里:

stream.Seek(pos, SeekOrigin.Begin);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接