我想尝试基本的加密和文件压缩,所以我的第一个问题是ByteReader是否是正确的读者?我的第二个最重要的问题是:当使用二进制阅读器时,如何循环到文件末尾?有没有办法按照How read a file into a seq of lines in F#中的说明像StreamReader一样做?
我想做以下事情:
let reader = new BinaryReader(File.Open("anyFile",FileMode.Open,FileAccess.Read)
let mutable data = []
while -condition i can't find- do
data <- [reader.readBytes()] :: data
//do fancy things with the achieved data
答案 0 :(得分:3)
如果您只想将流中的所有数据读取到内存中,那么方法Stream.CopyTo可能是最简单的解决方案:
use stream = File.Open("anyFile", FileMode.Open, FileAcces.Read)
use mem = new MemoryStream()
stream.CopyTo mem
let data = mem.ToArray()
答案 1 :(得分:0)
在意识到低级编程语言中需要缓冲区(我来自python)之后,我最终得到了以下代码。以上答案和this帖子非常有用
let test fileName =
use stream = File.Open(fileName, FileMode.Open, FileAccess.Read)
use reader = new BinaryReader(stream)
let bufferSize = 1000
let mutable buffer :byte array = Array.zeroCreate bufferSize
let mutable eof = false
while reader.Read(buffer,0,bufferSize) <> 0 && not eof do
let mutable position = 0
while position < buffer.Length && not eof do
let buf = buffer.[position]
if buf <> 0uy then
printfn "%A" buf
printfn "%A" (Convert.ToChar(buf))
position <- position + 1
else
eof <- true
test "test.txt"