I am getting the result streamreader object.
I want to convert the result into byte[].
How can i convert streamreader to byte[]?
Thanks
I am getting the result streamreader object.
I want to convert the result into byte[].
How can i convert streamreader to byte[]?
Thanks
Just throw everything you read into a
MemoryStream
and get the byte array in the end. As noted, you should be reading from the underlying stream to get the raw bytes.Or if you don't want to manage the buffers:
For everyone saying to get the bytes, copy it to
MemoryStream
, etc. - if the content isn't expected to be larger than computer's memory should be reasonably be expected to allow, why not just useStreamReader
's built inReadLine()
orReadToEnd()
? I saw these weren't even mentioned, and they do everything for you.I had a use-case where I just wanted to store the path of a SQLite file from a
FileDialogResult
that the user picks during the synching/initialization process. My program then later needs to use this path when it is run for normal application processes. Maybe not the ideal way to capture/re-use the information, but it's not much different than writing to/reading from an .ini file - I just didn't want to set one up for one value. So I just read it from a flat, one-line text file. Here's what I did:If you REALLY need a
byte[]
instead of astring
for some reason, using my example, you can always do:(Returning
toBytes
instead ofpath
.)If you don't want
ASCII
you can easily replace that withUTF8
,Unicode
, etc.A StreamReader is for text, not plain bytes. Don't use a StreamReader, and instead read directly from the underlying stream.
You can use this code:You shouldn't use this code:Please see the comment to this answer as to why. I will leave the answer, so people know about the problems with this approach, because I didn't up till now.
You can also use CopyTo:
or