Fetch contents from a URL into a string in C#
This article illustrates the different techniques to fetch contents from a URL into a string in C#.
1. Using WebClient class
To download the requested resource as a string, you can use the WebClient.DownloadString() method from the System.Net namespace. It takes the string containing the URI to download and returns a string containing the contents of the requested resource.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Net; public class Example { public static void Main() { String url = "https://code.jquery.com/jquery-3.6.0.min.js"; string s; using (WebClient client = new WebClient()) { s = client.DownloadString(url); } Console.WriteLine(s); } } |
2. Using HttpClient class
The recommended option is to use the HttpClient class from the System.Net.Http namespace. The HttpClient class provides the GetStringAsync() method, which sends a GET request to the specified Uri and asynchronously returns its content as a string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Net.Http; public class Example { public static void Main() { String url = "https://code.jquery.com/jquery-3.6.0.min.js"; string s; using (HttpClient client = new HttpClient()) { s = client.GetStringAsync(url).Result; } Console.WriteLine(s); } } |
3. Using WebRequest class
Finally, you can use the WebRequest.GetResponse() method to send a request to a resource and get a response. Here’s what the code would look like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Net; using System.IO; public class Example { public static void Main() { String url = "https://code.jquery.com/jquery-3.6.0.min.js"; using (StreamReader reader = new StreamReader(WebRequest.Create(url) .GetResponse().GetResponseStream())) { String s = reader.ReadToEnd(); Console.WriteLine(s); } } } |
That’s all about fetching contents from a URL into a string in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)