c# – How to get content from the cache in C #?


Hello! I am new to c # but know java well.

The question I'm asking now should be very easy: how to cache and get from the cache?

For example, when you access some Internet address, first search in the cache, if it is not in the cache, then I got this content from the Internet and put it in the cache

If you know C # and Java, below I gave the code in Java
This question can be answered without knowing Java.


import org.apache.commons.io.IOUtils; 

import java.io.IOException; 
import java.io.InputStream; 
import java.net.*; 
import java.util.List; 
import java.util.Map; 

public class Main { 
    public static void main(String[] args) throws Exception { 

        ResponseCache.setDefault(new ResponseCache() { 
            public CacheResponse get(URI uri, String rqstMethod,
                        Map<String, List<String>> rqstHeaders) throws IOException { 
                if (uri.toString().equals("http://google.com/")) { 
                    return new CacheResponse() { 
                        public Map<String, List<String>> getHeaders() throws IOException { 
                            return null; 

                        public InputStream getBody() throws IOException { 
                            return null; 
                return null; 

            public CacheRequest put(URI uri, URLConnection conn) throws IOException { 
                return null; 

        URLConnection c = new URL("http://google.com/").openConnection(); 

        String html = IOUtils.toString(c.getInputStream()); 


Please provide an example of a C # code similar to my code.


Let Response GetWebResponseFromUrl(string url) be some method (which you write yourself) to get Web content, then the answer to your question looks like this:

Dictionary<string, Response> ResponseCache = new Dictionary<string, Response>();

Response GetWebResponse(string url)
    if (!ResponseCache.ContainsKey(url))
        ResponseCache[url] = GetWebResponseFromUrl(url);
    return ResponseCache[url];
Scroll to Top