how to convert System.IO.Stream into string and then back to System.IO.Stream
I have property of Stream
type
public System.IO.Stream UploadStream { get; set; }
How can I convert it into a string
and send on to other side where I can again 开发者_如何学JAVAconvert it into System.IO.Stream
?
I don't know what do you mean by converting a stream to a string. Also what's the other side?
In order to convert a stream to a string you need to use an encoding. Here's an example of how this could be done if we suppose that the stream represents UTF-8 encoded bytes:
using (var reader = new StreamReader(foo.UploadStream, Encoding.UTF8))
{
string value = reader.ReadToEnd();
// Do something with the value
}
After some searching , other answers to this question suggest you can do this without knowing / using the string's encoding . Since a stream is just bytes , those solutions are limited at best . This solution considers the encoding:
public static String ToEncodedString(this Stream stream, Encoding enc = null)
{
enc = enc ?? Encoding.UTF8;
byte[] bytes = new byte[stream.Length];
stream.Position = 0;
stream.Read(bytes, 0, (int)stream.Length);
string data = enc.GetString(bytes);
return enc.GetString(bytes);
}
source - http://www.dotnetfunda.com/codes/show/130/how-to-convert-stream-into-string
String to Stream - https://stackoverflow.com/a/35173245/183174
精彩评论