سؤال

I want to take an attachment from an email and convert it to a base64 string so that I can store it as JSON.

In C#, I would get the attachment as a System.IO.Stream, read it into a byte array, and then use Convert.ToBase64String.

In F# though, I'm not sure how to this (I'm a beginner) and it feels like there is probably a much more functional way of doing things...?

هل كانت مفيدة؟

المحلول

F# combines functional style with object-oriented style, so that you can easily call .NET libraries from F#. Sometimes there are F#-specific libraries that give you a more functional style for some tasks (like list processing), but I don't think there is anything like that for base64 encoding and streams.

So, given a stream, you can read it into a buffer and then convert to base64 using .NET types as follows:

open System
open System.IO

let stream = // Some stream, for example: new MemoryStream([| 1uy; 2uy; 3uy; 4uy |])
let buffer = Array.zeroCreate (int stream.Length)
stream.Read(buffer, 0, buffer.Length)
Convert.ToBase64String(buffer)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top