从StreamReader VB.Net读取两行

时间:2016-05-21 20:58:24

标签: vb.net newline streamreader memorystream

我在从流阅读器中读取两行时遇到问题。我想阅读第一行,然后继续下一行。这是我的代码:

Public Function Read()
    Dim a As New MemoryStream(ASCII.GetBytes("[ID] " & vbCrLf & " salut" & vbCrLf))

    Debug.Print(client.ReadLine(a))
    Debug.Print(client.ReadLine(a))
End Function    


Public Function ReadLine(ByVal Data As MemoryStream)
    Dim sr As New StreamReader(Data)
    Return sr.ReadLine
End Function

输出结果为:

  

[ID]

一行。我在调试模式中检查了流,我看到第一次ReadLine调用后位置为15。所以我必须在第一个VbCrLf之后移动“指针”(一直到最后)。但我认为这不是正确的做法。我哪里错了?我甚至按值传递了流,所以它应该有效。

修改
我做了一些检查,似乎只有在传递流时,位置移动到最后。我在同一个Read函数中创建了一个流阅读器,并作为参数传递给了一个内存流。有效。我不知道为什么会这样。我还在找一件衣服。

1 个答案:

答案 0 :(得分:2)

目前尚不清楚你真正要做的是什么,但你并非真的尝试从[a] StreamReader 中读取两行,你试图读取一个使用相同的数据源/缓冲区从两个不同的流读取器一次排队。

app.post('/reply', function(req, res){
  var commenterId = req.body.userId; // this is the id of the original commenter, not the replier
  User.findOne({'_id':commenterId}, function(err, user){
    user.send({'replied': req.user._id}); // this is what I need to do, and
  //I don't know if this specific code works and that's why I'm asking if there is a way to do it with socket.io,
  // io.to(socketId).emit('reply', 'some reply text here...'); // but if I do this I don't know how to get the socketId!
  //Is there even a way to do this? Maybe with another module,
  //or some express function I don't know about? And if it is done with express how would
  //the client side code, look like? Thank you!
  });
  res.end();
});

如果您在第一个Dim buff = Encoding.ASCII.GetBytes("[ID] " & vbCrLf & " salut" & vbCrLf) Using ms As New MemoryStream(buff) Using sr As New StreamReader(ms) Console.WriteLine(sr.ReadLine()) Console.WriteLine("memstream poition: " & ms.Position) Console.WriteLine(sr.ReadLine()) Console.WriteLine("memstream poition: " & ms.Position) Console.WriteLine(sr.ReadLine()) End Using End Using 上设置断点,则会看到sr.ReadLine()位置已更改。如果您将鼠标悬停在MemoryStream变量上,您就会明白原因:

enter image description here

sr有一个缓冲区,默认为1024字节。您可以将该缓冲区与代码中创建的缓冲区进行比较,看它们是否相同。还有一个Streamreader重载,允许您指定大小:

StreamReader

尝试从具有不同(新)Public Sub New(stream As System.IO.Stream, encoding As System.Text.Encoding, detectEncodingFromByteOrderMarks As Boolean, bufferSize As Integer) 的单个数据流中读取不会起作用,因为前一个数据流已经消耗了一些数据。您应该能够将数千行读入数组或列表中,您的代码可以将其用作行缓冲区。