vb.net 教程 4-9 二进制文件读写 3

前端之家收集整理的这篇文章主要介绍了vb.net 教程 4-9 二进制文件读写 3前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在上一节的基础上,本节做一些扩展。

判断文件是什么类型,为了简化操作,仅仅只判断是否可执行文件、png文件、gif文件、jpeg文件

上述文件对应的前面几个字节是:

可执行文件:4D 5A
PNG文件:89 50 4E 47
Jpeg文件:FF D8 FF E0 00 10 4A 46 49 46
gif89文件:47 49 46 38 39 61

需要说明的是,我没有真正去查找相关文件格式信息,这里只是为了说明二进制文件的读取,以上资料是用WinHex查看得来的,不一定就是真正的文件头,

需要相关的文件头信息,请网上自行搜索

相关代码如下:

    Private Sub btnOpenFile_Click(sender As Object,e As EventArgs) Handles btnOpenFile.Click
        Dim filename As String
        If OpenFileDialog1.ShowDialog <> DialogResult.OK Then
            Exit Sub
        End If
        filename = OpenFileDialog1.FileName
        lblFilePath.Text = filename
        txtFileType.Text = checkFileType(filename)
    End Sub

具体实现代码

    Private Function checkFileType(ByVal filename As String) As String
        Try
            Dim fs As FileStream = New FileStream(filename,FileMode.Open)
            If fs.Length < 10 Then Return "未知文件"
            Dim br As BinaryReader = New BinaryReader(fs)
            Dim byteRead() As Byte
            Dim intReadLength As Integer = 10
            ReDim byteRead(intReadLength - 1)

            byteRead = br.ReadBytes(intReadLength)

            br.Close()
            fs.Close()

            If byteRead(0) = Convert.ToInt32("4D",16) And byteRead(1) = Convert.ToInt32("5A",16) Then Return "可执行文件"
            If byteRead(0) = Convert.ToInt32("89",16) And byteRead(1) = Convert.ToInt32("50",16) And byteRead(2) = Convert.ToInt32("4E",16) _
                And Convert.ToInt32("47",16) Then Return "PNG文件"
            If byteRead(0) = Convert.ToInt32("47",16) And byteRead(1) = Convert.ToInt32("49",16) And byteRead(2) = Convert.ToInt32("46",16) _
                And byteRead(3) = Convert.ToInt32("38",16) And byteRead(4) = Convert.ToInt32("39",16) _
                And byteRead(5) = Convert.ToInt32("61",16) Then Return "Gif文件"
            If byteRead(0) = Convert.ToInt32("FF",16) And byteRead(1) = Convert.ToInt32("D8",16) And byteRead(2) = Convert.ToInt32("FF",16) _
                And byteRead(3) = Convert.ToInt32("E0",16) And byteRead(4) = Convert.ToInt32("00",16) _
                And byteRead(5) = Convert.ToInt32("10",16) And byteRead(6) = Convert.ToInt32("4A",16) _
                And byteRead(7) = Convert.ToInt32("46",16) And byteRead(8) = Convert.ToInt32("49",16) _
                And byteRead(9) = Convert.ToInt32("46",16) Then Return "Jpeg文件"


                Return ""
        Catch ex As Exception
            Return ""
        End Try

    End Function

运行时如图:


由于二进制文件写入和读取比较类似,这里不再累述,

在下一节中,我们将学习做一个存档文件修改器,将会有二进制文件读写的详细代码


由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。

学习更多vb.net知识,请参看 vb.net 教程 目录

原文链接:https://www.f2er.com/vb/256523.html

猜你在找的VB相关文章