2012-08-04 66 views

回答

2

您可以繼承Stream!這裏有一個ProgressStream從文件中讀取:

Public Class ProgressStream 
    Inherits FileStream 

    Public Event ProgressChanged(sender As ProgressStream, progress As Integer) 

    Public Sub New(fileName As String) 
     MyBase.New(fileName, FileMode.Open, FileAccess.Read) 
    End Sub 

    Public ReadOnly Property Progress() As Integer 
     Get 
      Return CInt(Me.Position/Me.Length * 100) 
     End Get 
    End Property 

    Public Overrides Function Read(array() As Byte, offset As Integer, count As Integer) As Integer 
     Read = MyBase.Read(array, offset, count) 
     RaiseEvent ProgressChanged(Me, Me.Progress) 
    End Function 
End Class 

只是處理ProgressChanged事件。

同樣的方法適用於所有其他類型的數據流,你也可以用它來作爲所需的所有而不是一次讀取文件的某些其他長時間運行的任務。

2

一種常見的方法是使用TransformBlockTransformFinalBlock並計算以塊的哈希值。這允許你不關心你正在使用的流的類型,或者你想散列多個流(比如說一個目錄中的所有文件)。

這裏有一個小例子:

Using stream As New FileStream("C:\somefile.dat", FileMode.Open), 
     hash As New SHA512Cng() 
    Const BUFFER_SIZE As Integer = 2048 
    Dim buffer(BufferSize - 1) As Byte 
    Dim bytesRead As Integer 

    Do 
     bytesRead = stream.Read(buffer, 0, BUFFER_SIZE) 
     hash.TransformBlock(buffer, 0, bytesRead, buffer, 0) 

     Dim percentComplete = stream.Position/stream.Length * 100 
     'Handle percentComplete here somehow, perhaps with an event 
    Loop While stream.Length - stream.Position > BUFFER_SIZE 

    bytesRead = stream.Read(buffer, 0, BUFFER_SIZE) ' read the final block 
    hash.TransformFinalBlock(buffer, 0, bytesRead) 

    'We're now 100% complete, raise an event with 100% completion 
    Dim theHash = hash.Hash 'The final hash values 
End Using 

較小的緩衝區大小,更細粒度的結果,但可能以性能爲代價。

+0

哎呀,我猜我錯過了。謝謝! – Ryan 2012-08-04 17:14:45

相關問題