VB - 如何读写二进制文件?

6

我该如何从任意文件中读取原始字节数组...

 Dim bytes() as Byte

我需要将这个字节数组写回到一个新文件中吗?

我需要它作为一个字节数组,在其中进行一些处理。


我目前正在使用:

读取:

 Dim fInfo As New FileInfo(dataPath)
 Dim numBytes As Long = fInfo.Length
 Dim fs As New FileStream(dataPath, FileMode.Open, FileAccess.Read)
 Dim br As New BinaryReader(fs)
 Dim bytes As Byte() = br.ReadBytes(CInt(numBytes))
 br.Close()
 fs.Close()

编写代码

Dim fs As System.IO.FileStream
fs = New System.IO.FileStream(outpath, System.IO.FileMode.Create)
fs.Write(bytes, 0, bytes.Length)
fs.Close()

你可以发一下你的尝试吗? - Mitch Wheat
类似于https://dev59.com/73M_5IYBdhLWcg3wRw11...但不同的是,C#可以做VB.NET无法做到的事情。 - Robin Rodricks
1
“C#可以做一些VB.NET无法做到的事情” - 除了XML处理的某些方面,还能说出一些吗? - Mitch Wheat
1
@Jeremy:我想不出与问题相关的语言差异。 - AnthonyWJones
我是否需要支持LINQ,因为我要针对NET 2.0? - Robin Rodricks
据我所知,您不能在VB中使用unsafe关键字。 - davidtbernal
3个回答

16
Dim data() as Byte = File.ReadAllBytes(path1)
File.WriteAllBytes(path2, data)

5
System.IO.File.ReadAllBytes("myfile.txt")

3

试试这个:

Dim bytes() as Byte
bytes = File.ReadAllBytes(fileName)
'' # Do stuff to the array
File.WriteAllBytes(otherFileName, bytes)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接