Download string from URL using a portable class library (PCL)
c#, portable-class-library, webclient, windows-phone-8, windows-runtime
Solution
Install the NuGet packages:
- `Microsoft.Bcl.Async`, which adds `async`/`await` support to PCLs.
- `Microsoft.Net.Http`, which adds `HttpClient` support to PCLs.
Then you can do it the easy way:
var client = new HttpClient();
var data = await client.GetStringAsync(url);
Problem
I'm trying to download a string from ANY webpage within my portable class library. I've created the most basic setup: - created a new PCL project - compatible with WP8 and WinRT as well as the compulsory components such as Silverlight As WebClient is not compatible across these systems, it is not possible to use: ``` string data = new WebClient().DownloadString(); ``` I've tried using this as well (uses this): ``` HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = HttpMethod.Get; HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); string data = "" using (var sr = new StreamReader(response.GetResponseStream())) { data = sr.ReadToEnd(); } ``` However, when I call the second set of code from an external C# application referencing the PCL, the debugger simply fails with NO warning or error message on: ``` request.GetResponseAsync(); ``` Is there an easy way to download a string that I'm missing? *also, why would the debugger simply exit with no explanation? Edit: Here is another method I have attempted - based on an answer already provided. Again, this method simply exits and force closes the debugger. PCL Method: ``` public static async Task<string> DownloadString() { var url = "http://google.com"; var client = new HttpClient(); var data = await client.GetStringAsync(url); return data; } ``` Calling method: ``` private static async void Method() { string data = await PCLProject.Class1.DownloadString(); return data; } ```