Reading from memory stream to string
Solution 1:
If you'd checked the results of stream.Read
, you'd have seen that it hadn't read anything - because you haven't rewound the stream. (You could do this with stream.Position = 0;
.) However, it's easier to just call ToArray
:
settingsString = LocalEncoding.GetString(stream.ToArray());
(You'll need to change the type of stream
from Stream
to MemoryStream
, but that's okay as it's in the same method where you create it.)
Alternatively - and even more simply - just use StringWriter
instead of StreamWriter
. You'll need to create a subclass if you want to use UTF-8 instead of UTF-16, but that's pretty easy. See this answer for an example.
I'm concerned by the way you're just catching Exception
and assuming that it means something harmless, by the way - without even logging anything. Note that using
statements are generally cleaner than writing explicit finally
blocks.
Solution 2:
string result = System.Text.Encoding.UTF8.GetString(fs.ToArray());