从端口读取字节并将其写入文件的快速方法

时间:2018-12-07 11:21:43

标签: vb.net file

我试图在一个周期内从com端口读取1536个字节,并将其附加到bin文件中。好像太慢了10sec = 100kb写入文件。我正在使用USB FS,因此问题不在USB的速度上。 我怎么称呼潜艇:

    If receivedData.Contains("mcu_r") Then
            Call Read(spObj, 1536)
            receivedData = vbNullString


            Exit Sub
        End If

读取并保存到文件sub:

 Public Function Read(ByVal port As SerialPort, ByVal count As Integer) As Byte()
        Dim buffer(count - 1) As Byte
        Dim readBytes As Integer
        Dim totalReadBytes As Integer
        Dim offset As Integer
        Dim remaining As Integer = count

        Try
            Do
                readBytes = port.Read(buffer, offset, remaining)
                offset += readBytes
                remaining -= readBytes
                totalReadBytes += readBytes
            Loop While remaining > 0 AndAlso readBytes > 0
        Catch ex As TimeoutException
            ReDim Preserve buffer(totalReadBytes - 1)
        End Try
        Using vFs As New FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\myfile.bin", FileMode.Append) 'save
            vFs.Write(buffer, 0, 1536)
        End Using
        'lable_count = lable_count + 2048
        'Dim strTemp As New StringBuilder(512 * 2)
        'For Each b As Byte In buffer
        '    strTemp.Append(Conversion.Hex(b))
        'Next

        'Dim builder As New StringBuilder(strTemp.ToString)
        'Dim startIndex = builder.Length - (builder.Length Mod 2)

        'For i As Int32 = startIndex To 2 Step -2
        '    builder.Insert(i, " "c)
        'Next i
        'Form1.RichTextBox1.Text &= builder.ToString()
        'Form1.RichTextBox1.Text &= strTemp.ToString
        Dim BytesToSend(0) As Byte
        Dim OutBuffer
        BytesToSend(0) = &H11             ' call Dump eeprom (44)
        'dummy
        Dim v As String
        OutBuffer = BytesToSend

        ' Bytes are outputted in the order of their Index Number(Index)!

        Form1.spObj.Write(OutBuffer, 0, OutBuffer.length)
        Return buffer

    End Function

0 个答案:

没有答案