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.

Download Code

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.

Download Code

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:

Download Code

That’s all about fetching contents from a URL into a string in C#.