I recently was working on a Silverlight 2 project and needed to "phone home" from the .xap back to the server of origin to get a text file from the server. It wasn't completely obvious how to do this at first, so I figured I'd share the code I wrote if others need to do something similar. Note a couple things:

  1. You'll need to add a reference to System.Net.dll and using statements for System.Net and System.IO.
  2. The ASP.NET WebDev server used for development will run the project on a random port. You can change this behavior so you have a consistent port number. Click on the project node in Solution Explorer and open the properties window (press F4). Change the “Use dynamic ports” property from True to False and edit the port number.
  3. If you try to go to a server other than the server of origin, you'll most likely run into cross site scripting issues.

 

    public partial class Page : UserControl 
{
public Page() { InitializeComponent(); this.Loaded += new RoutedEventHandler(Page_Loaded); }

    <span style="color: rgb(0,0,255)">void</span> Page_Loaded(<span style="color: rgb(0,0,255)">object</span> sender, <span style="color: rgb(43,145,175)">RoutedEventArgs</span> e)
    {
        <span style="color: rgb(0,128,0)">//you may need to change this path depending on your web server

WebRequest request = WebRequest.Create(new Uri("http://localhost:4386/io_web/textfile.txt";));
request.Method = "GET"; request.ContentType = "text/plain"; request.BeginGetResponse(new AsyncCallback(ResponseReady), request);

    }

    <span style="color: rgb(0,0,255)">void</span> ResponseReady(<span style="color: rgb(43,145,175)">IAsyncResult</span> asyncResult)
    {
        <span style="color: rgb(43,145,175)">WebRequest</span> request = asyncResult.AsyncState <span style="color: rgb(0,0,255)">as</span> <span style="color: rgb(43,145,175)">WebRequest</span>;
        <span style="color: rgb(0,0,255)">using</span> (<span style="color: rgb(43,145,175)">WebResponse</span> response = request.EndGetResponse(asyncResult))
        {
            <span style="color: rgb(0,0,255)">using</span> (<span style="color: rgb(43,145,175)">Stream</span> responseStream = response.GetResponseStream())
            {
                <span style="color: rgb(43,145,175)">StreamReader</span> reader = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">StreamReader</span>(responseStream);
                <span style="color: rgb(0,0,255)">string</span> s = reader.ReadLine();
                System.Diagnostics.<span style="color: rgb(43,145,175)">Debug</span>.WriteLine(s);
            }
        }
    }        

}</pre>