Tuesday, September 7, 2010

Download a file in Silverlight from the server

For downloading a file form  the server we have several ways .The following  example i have used the traditional asp.net handlers ie the ashx.

All that what we have to do when downloading a file from silverlight is that
we need to navigate to handler that have created for the download.

The  following code sippnet shows the handler

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.UI;

namespace SLMemoryLeakSample.Web
    /// Summary description for $codebehindclassname$
    public class FileDownload : IHttpHandler

        public void ProcessRequest(HttpContext context)
            context.Response.Buffer = true;
            context.Response.AddHeader("Content-Disposition", "attachment;filename=Test.doc");
            context.Response.ContentType = "application/ms-Excel";
            context.Response.WriteFile("New Microsoft Office Word Document.docx");

        public bool IsReusable
                return false;
As you can see the the code that have written inside the Process Request basically  we just write the file into the output stream so that the file will be available in the client

Now step is the real magic of the silvelight especally the HyperLink button we have something called the NavigateUri which actually  call this handler

We can set the TagetName property to what ever you want from the avaiable .If we didnt set the target property name we will probably  get an error since the silverlight expects another xaml page

Enjoy coding............................


Post a Comment