40

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 convert it into System.IO.Stream?

BanksySan
  • 27,362
  • 33
  • 117
  • 216
SOF User
  • 7,590
  • 22
  • 75
  • 121

2 Answers2

95

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
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • problem is one i use this string value and send it to other side using xml serlization it gives error [XmlElement("UploadStream")] public string UploadStream { get; set; } – SOF User Nov 30 '10 at 17:22
  • It seems that you are trying to serialize a stream to XML. If this is the case please provide more details about your scenario. Where are you trying to send this serialized XML to? – Darin Dimitrov Nov 30 '10 at 17:30
  • Actually we working on Silverlight application and using RIA services made by client using this service we send string to our asp.net application. – SOF User Nov 30 '10 at 17:35
  • now simple qustion is on silverlight end i have stream object file i want it to send to that side via string values. i decided that i will first convert stram object into string and then wrap it into xml object – SOF User Nov 30 '10 at 17:36
  • 2
    @SOFUser perhaps you should edit your question to include more detail, and perhaps a code sample of what it is you are trying to do. This might help you get better answers that are "what you are looking for". Your question is kind of vague, and we can't help you diagnose the error you are getting without more details. – bbosak Oct 14 '11 at 01:38
4

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

LostNomad311
  • 1,975
  • 2
  • 23
  • 31