Thursday, August 19, 2010

Silverlight: Download image to byte[]

public delegate void DownloadPhotoCompleted(byte[] imageBytes);
public event DownloadPhotoCompleted DownloadPhotoCompletedEvent;

void worker_DoWork(object sender, DoWorkEventArgs e)
{
      WebClient wc = new WebClient();
      wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
      wc.OpenReadAsync(uri);
}

void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
      int length = (int)e.Result.Length;
      BinaryReader br = new BinaryReader(e.Result);
      byte[] buffer = new byte[length];
      using (br)
      {
            for (int i = 0; i < length; i++)
            {
                  buffer[i] = br.ReadByte();
            }
      }


      if (DownloadPhotoCompletedEvent != null)
            DownloadPhotoCompletedEvent(buffer);
}


Note that the external site needs to have a crossdomain.xml or clientaccesspolicy.xml defined to allow access by your application. If not you will encounter a System.SecurityException.

No comments:

Post a Comment