Convert string to stream

I am trying to convert a string to a stream so that I can read the specified stream. So what I do is that I convert the string to a char array and write each char / byte to a MemoryStream, which I later transfer to BinaryReader

The way I tried to implement this is as follows:

let readData (data:string) = 
    let ms = new MemoryStream()
    let bw = new BinaryWriter(ms)
    data.ToCharArray() |> Array.iter (fun x -> bw.Write((byte)x))
    let br = new BinaryReader(bw.BaseStream)
    readStream 0 br

Later I will try to read it as

let rec readStream c (br:BinaryReader) =
    let bytes = br.ReadBytes 16
    printfn "Size read is: %i" bytes.Length

But my result is always 0 bytes, and I checked that the string is not equal to 0 bytes. And I tried calling Flush on a MemoryStream.

Am I missing something fundamental or is this another obvious way to do this?

+4
source share
2 answers

MemoryStream. , , :

let bytes = System.Text.Encoding.UTF8.GetBytes data
let stream = MemoryStream( bytes )

. , , . , , , Encoding.GetBytes:

let readData (data:string) = System.Text.Encoding.UTF8.GetBytes data

.

, (byte)x, , -, , " ", #, . "casting" F # - ( :> :?>), / (.. ). . , F #.

byte. , F # , byte x.

char , , char ( , ?) , , char ASCII ( ), , . , char:

let x = 'a'
let y = char (byte x)
> val y : char = 'a'  // This worked

let x = ''
let y = char (byte x)
> val y : char = '\019'  // Oops
+9

MemoryStream, . reset , . readStream

br.BaseStream.Position <- 0L
+2

Source: https://habr.com/ru/post/1678456/


All Articles