字节>字符串>字节>文件VB

时间:2016-05-13 13:34:57

标签: vb.net string byte bytearray

我想将字节转换为字符串并返回,我已经尝试过这个:

Public Class Form1

        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim bytes() As Byte = My.Computer.FileSystem.ReadAllBytes("C:\Archive.zip")

            Dim filestream As System.IO.FileStream = System.IO.File.Create("C:\Archive2.zip")

            Dim info As Byte() = fromstringtobyte(frombytetostring(bytes))
            filestream.Write(info, 0, info.Length)
            filestream.Close()
        End Sub
        Private Function frombytetostring(ByVal b() As Byte)
            Dim s As String
            s = Convert.ToBase64String(b)
            Return s

        End Function
        Private Function fromstringtobyte(ByVal s As String)
            Dim b() As Byte
            b = System.Text.Encoding.UTF8.GetBytes(s)
            Return b
        End Function
    End Class

创建的新文件已损坏。 你能推荐一下其他解决方案吗?

抱歉我的英语不好,这不是我的主要语言。

2 个答案:

答案 0 :(得分:0)

您的字节到字符串转换是错误的。你需要使用:

System.Text.Encoding.[your encoding].GetString(bytes)

来源:

How to: Convert an Array of Bytes into a String in Visual Basic

How to: Convert Strings into an Array of Bytes in Visual Basic

您可能还想阅读此内容以确定要使用的编码:The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

答案 1 :(得分:-1)

我找到了答案,新代码是:

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim bytes() As Byte = My.Computer.FileSystem.ReadAllBytes("C:\Program Files (x86)\Windows Repair Pro\Windows Repair Pro (All In One) 3.8.7\Tweaking.com - Windows Repair Portable\Archive.zip")

        Dim filestream As System.IO.FileStream = System.IO.File.Create("C:\Program Files (x86)\Windows Repair Pro\Windows Repair Pro (All In One) 3.8.7\Tweaking.com - Windows Repair Portable\Archive2.zip")

        Dim info As Byte() = fromstringtobyte(frombytetostring(bytes))
        filestream.Write(info, 0, info.Length)
        filestream.Close()
    End Sub
    Private Function frombytetostring(ByVal b() As Byte)
        Dim s As String
        s = BitConverter.ToString(b)
        Return s.Replace("-", "")
    End Function
    Private Function fromstringtobyte(ByVal s As String)
        Dim B() As Byte = New Byte(s.Length / 2 - 1) {}
        For i As Integer = 0 To s.Length - 1 Step 2
            B(i / 2) = Convert.ToByte(s.Substring(i, 2), 16)
        Next
        Return B
    End Function

End Class