CVertex
CVertex

Reputation: 18237

.NET HttpRequests using the Windows system Cache

I'm using either WebClient or HttpRequest/REsponse to make http calls for images.

I'm not sure how caching specifically works for browsers, but is there a way to enable either WebClient or WebHttpRequest to use the systems "temporary internet files" cache that the browser utilize?

Or, do I have to write my own disk cacher?

Upvotes: 1

Views: 462

Answers (2)

Martin Vobr
Martin Vobr

Reputation: 5823

You can instruct the WebRequest to use system cache by setting the CachePolicy property.

Following code (taken from MSDN) caches requests for one day. The cache is stored at the temporay internet files folder of the current user (at least on Windows XP).

// Create a policy that allows items in the cache
// to be used if they have been cached one day or less.
HttpRequestCachePolicy requestPolicy = 
  new HttpRequestCachePolicy (HttpCacheAgeControl.MaxAge,
  TimeSpan.FromDays(1));

WebRequest request = WebRequest.Create (resource);

// Set the policy for this request only.
request.CachePolicy = requestPolicy;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

// Determine whether the response was retrieved from the cache.
Console.WriteLine ("The response was retrieved from the cache : {0}.",
 response.IsFromCache);

Stream s = response.GetResponseStream ();
// do something with the response stream
s.Close();
response.Close();

Upvotes: 4

core
core

Reputation: 33079

If you're making HTTP requests and you want your requests to access a local cache if the requested resource has already been requested, you'll have to write your own cache.

There are many potential implementations. It really depends on how many different resources you expect to request, and how often.

Upvotes: 0

Related Questions