我正在为我的应用程序中的API端点创建自定义流。该流需要具有我不想进入的自定义逻辑,但足以说我不能使用内置流类。为什么System.IO.StreamReader不能从我的自定义流中读取?
我做了必要的最低限度,以实现一个只读流(从System.IO.Stream继承),我已经验证了System.IO.BinaryReader类可以从我的流读取:
Dim reader As New System.IO.BinaryReader(GenerateStream(business, logic))
Dim enc As New System.Text.ASCIIEncoding
Dim contents As String = enc.GetString(reader.ReadBytes(CType(reader.BaseStream.Length, Int32)))
字符串“contents”包含整个流的正确字符串。
不过,我想能够允许使用System.IO.StreamReader类的:
Dim reader As New System.IO.StreamReader(GenerateStream(business, logic), System.Text.Encoding.ASCII)
Dim contents As String = reader.ReadToEnd
但无论什么原因,总是ReadToEnd的返回空字符串。
任何想法?
这里的流:
Public Overrides ReadOnly Property CanRead() As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property CanSeek() As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property CanWrite() As Boolean
Get
Return False
End Get
End Property
Public Overrides Sub Flush()
'this method intentionally left blank'
End Sub
Public Overrides ReadOnly Property Length() As Long
Get
Return 'some business logic'
End Get
End Property
Public Overrides Property Position() As Long
Get
Return bytePosition
End Get
Set(ByVal value As Long)
Throw New System.NotSupportedException
End Set
End Property
Public Overrides Function Read(ByVal buffer() As Byte, ByVal offset As Integer, ByVal count As Integer) As Integer
'I return 0 on an end of stream, otherwise the # of bytes successfully read.'
End Function
Public Overrides Function Seek(ByVal offset As Long, ByVal origin As System.IO.SeekOrigin) As Long
Throw New System.NotSupportedException
End Function
Public Overrides Sub SetLength(ByVal value As Long)
Throw New System.NotSupportedException()
End Sub
Public Overrides Sub Write(ByVal buffer() As Byte, ByVal offset As Integer, ByVal count As Integer)
Throw New System.NotSupportedException()
End Sub
数据是字符(在这种情况下用ascii编码)。我没有试过用BinaryReader读取流的结尾,但是我已经验证了你可以用BinaryReader读/结束,并且你得到正确的输出。 虽然也许如果我实现寻求问题将会消失。尽管我确实错过了“ReadToEnd”的描述。如果寻求解决问题,这是答案。 问题中显示ReadToEnd的BinaryReader实现。 – 2010-01-26 15:43:59
问题确实存在于我的阅读方法中。如果/ current/read达到流的末尾,我的读取方法将返回0。现在只有在从空流读取时才返回0。 – 2010-01-27 19:19:42
不,寻求或不寻求不是问题。正如你发现的那样,你的接口实现必须是正确的。如果没有看到所有相关的代码,就很难找到这样的错误......;) – Abel 2010-01-28 02:03:43