WebClient class is used in Silverlight to asynchronously download or read a file from a particular URI.
1. WebClient class is under System.Net namespace.
2. This can retrieve data from any format of service. This can retrieve data in JSON, POX, and REST etc. format.
3. WebClient makes the entire request asynchronously. So it does not block any other operation.
4. On basis of data type of response from URI, we can choose class to parse the response data. If response is JOSN, we can use DataContractJSONSerliazer to parse response data.
5. Any type of file including Media, Images, and XML etc. can be downloaded using WebClient class.
Let us read a XML file asynchronously using WebClient class.
1. Add XML file named Data.xml in the client bin folder. Right click on client Bin folder and add a new item then select XML file from Data tab. Give name of the file as Data.xml.
Shiv Prasad Koirala
2. Once Data.xml file is in place inside client bin folder, let us design XAML page. We will put one Button and one TextBlock.
On click event of button, we will make asynchronous call to read Data.xml file. After successful reading, we will bind xml response to TextBlock.
3. On click event of button, we will read Data.xml file asynchronously.
At time of creation of URL either we can provide absolute URI or relative. In our example Data.xml file is in client bin folder so we are providing relative address.
In OpenReadCompleted event handler, we will parse XML file and bind response to TextBlock.
For reference full code is given below,
public partial class MainPage : UserControl
btnDemo.Click +=new RoutedEventHandler(btnDemo_Click);
private void btnDemo_Click(object sender, RoutedEventArgs e)
WebClient client = new WebClient();
Uri uritoXML = new Uri("Data.xml",UriKind.Relative);
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
Stream s = e.Result;
StreamReader strReader = new StreamReader(s);
txtDataFromXml.Text = strReader.ReadToEnd();