M.Y. Babt
M.Y. Babt

Reputation: 2891

Calling the File.ReadAllBytes method in F#

Here is a sample of my code:

let getAllBooks bookDirectory =
    seq {yield! Directory.GetFiles(bookDirectory)}
    |> Seq.map (fun eachFile -> eachFile.ReadAllBytes)

It fails to work. What is wrong? What should I write instead?

Upvotes: 1

Views: 568

Answers (1)

Nikon the Third
Nikon the Third

Reputation: 2831

Like you said in the title, the function is called File.ReadAllBytes ;)

It is a static method of the System.IO.File class, and therefore has to be called on the File type, not some instance:

open System.IO

let getAllBooks bookDirectory =
    seq {yield! Directory.GetFiles (bookDirectory) }
    |> Seq.map (fun eachFile -> File.ReadAllBytes eachFile)

Btw, this code could be improved, since the result of GetFiles is an array, which is also a seq:

open System.IO

let getAllBooks bookDirectory =
    Directory.GetFiles bookDirectory
    |> Seq.map (fun eachFile -> File.ReadAllBytes eachFile)

Furthermore, you could simply pass the ReadAllBytes function directly to map:

open System.IO

let getAllBooks bookDirectory =
    Directory.GetFiles bookDirectory
    |> Seq.map File.ReadAllBytes

Finally, you can get rid of the function parameter as well, if you like:

open System.IO

let getAllBooks =
    Directory.GetFiles
    >> Seq.map File.ReadAllBytes

Update for the comment:

I have an additional question: How may I convert a byte array into its numeric equivalent?

You may use the static methods in the System.BitConverter class, for example System.BitConverter.ToInt32:

open System

let array = [| 0x00uy; 0x10uy; 0x00uy; 0x00uy |]

BitConverter.ToInt32 (array, 0)
|> printfn "Array as Int32: %d"
// Prints: Array as Int32: 4096

Don't overlook the ToString method in there, which can convert a byte array to a hex string:

BitConverter.ToString array
|> printfn "%s"
// Prints: 00-10-00-00

All available conversion methods can be found on MSDN.

Upvotes: 3

Related Questions