37

I have what seems like it should be a simple question, but I can't find an answer to it anywhere. Given the following code:

    using System.Net.Http;
    ...
    StringContent sc = New StringContent("Hello!");
    string myContent = ???;

What do I need to replace the ??? with in order to read the string value from sc, so that myContent = "Hello!"?

.ToString just returns System.String, as does .ReadAsStringAsync. How do I read out what I've written in?

IAmErickson
  • 373
  • 1
  • 3
  • 6
  • 2
    I recommend utilizing the MSDN https://msdn.microsoft.com/en-us/library/system.net.http.stringcontent%28v=vs.118%29.aspx – Jace Mar 28 '16 at 21:43
  • When I call `await sc.ReadAsStringAsync();` I get the string "Hello!". If you're getting `System.String` you're doing something wrong. – Craig W. Mar 28 '16 at 21:48

1 Answers1

66

You can use ReadAsStringAsync() method, then get the result using await statement or Result property:

StringContent sc = new StringContent("Hello!");

string myContent = await sc.ReadAsStringAsync();
//or
string myContent = sc.ReadAsStringAsync().Result;
Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53
  • I must've tried this half a dozen different ways, and every time, I couldn't get the actual content. I'm not sure what I was doing wrong - I was trying to use ReadStringAsSync - but I just tried it again and sc.ReadAsStringAsync().Result does indeed work, so thanks! – IAmErickson Mar 28 '16 at 22:31
  • 2
    Async as in asynchronous – Adam White Nov 12 '16 at 17:59