---
title: "在Silverlight中使用WebClient 下载资源时存在缓存问题的解决方案"
author: "winzenghua"
date: "2009-01-09T11:03:00Z"
tags: []
slug: "silverlight-webclient"
draft: false
lastmod: "2009-01-09T11:03:00Z"
id: 952914
url: "https://java4gis.iteye.com/blog/952914"
---

**问题：**

**在Silverlight中使用WebClient 下载资源时，存在缓存问题。当资源更新的时候，下载后的内容未更新。**

解决方案一：

既然资源的下载依赖于URL，可以动态改变URL，来获取最新的资源。

public void LoadStringResource(string relativeFileName)  
{  
WebClient xmlClient = new WebClient();  
xmlClient.Encoding = System.Text.Encoding.Unicode;  
xmlClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(XMLFileLoaded);  
relativeFileName = relativeFileName +"?eking=" + random.Next().ToString();  
xmlClient.DownloadStringAsync(new Uri(relativeFileName));  
}

void XMLFileLoaded(object sender, DownloadStringCompletedEventArgs e)  
{  
if (e.Error == null)  
{  
fileData = e.Result;

SampleDrawings = new DrawingStorage(fileData);  
drawingXml = SampleDrawings.Storage;  
if (drawingXml != null)  
{  
LoadDrawing(drawingXml, isRunMode);  
}  
}  
}

**EKING/王毅，2009, TPRI 版本所有。**

解决方案二：

将下面的代码加到 silverlight 库中或直接加在应用程序中。

public static class WebClientExtensions  
{  
public static void DownloadStringAsync(this WebClient client, Uri uri, object user\_token, bool fresh\_copy)  
{  
if (!fresh\_copy)  
{  
client.DownloadStringAsync(uri, user\_token);  
}  
else  
{  
client.DownloadStringAsync(new Uri(uri.AbsoluteUri + "?" + Guid.NewGuid().ToString()), user\_token);  
}  
}  
}  
}

![](http://p.blog.csdn.net/images/p_blog_csdn_net/wangyihust/EntryImages/20090109/SlReal.jpg)