我正在爲我的應用程序中的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