Search code examples
vb.netcycle

VB.NET Speed up cycle function


I have this function to write bytes in a bin file.

    Public Shared Function writeFS(path As String, count As Integer) As Integer
        Using writer As New BinaryWriter(File.Open(path, FileMode.Open, FileAccess.Write, FileShare.Write), Encoding.ASCII)
            Dim x As Integer
            Do Until x = count
                writer.BaseStream.Seek(0, SeekOrigin.End)
                writer.Write(CByte(&HFF))
                x += 1
            Loop
        End Using
        Return -1
    End Function

I have a textBox that is the count value. Count is the number of byte to write into the file.

The problem is when i want to write 1mb+ it take like 10+ seconds because of the cycle.

I need a better/faster way to write hex value FF at the end of file 'value' times.

I'm sorry if i've not explained very well.


Solution

  • This should be better:

    Public Shared Function writeFS(path As String, count As Integer) As Integer
        Using writer As New BinaryWriter(File.Open(path, FileMode.Open, FileAccess.Write, FileShare.Write), Encoding.ASCII)
            Dim x As Integer
            Dim b as Byte
            b = CByte(&HFF)
            writer.BaseStream.Seek(0, SeekOrigin.End)
            Do Until x = count
                writer.Write(b)
                x += 1
            Loop
        End Using
        Return -1
    End Function
    

    That way you're not calling CByte every time. And there is no need to move to the end of the stream after each write.