Wednesday, August 19, 2009

force download of remote file

Many times we want 2 enable 2 users to download files from our web site
just put this function in the Page_Load function and then the users will be enable to download remote files from any web site (note that the function parameter is a virtual path!):

private void forceDownloadRemoteFile(string sFileVirtualPath)
{
string sFileName = System.IO.Path.GetFileName(sFileVirtualPath);
WebClient oWebClient = new WebClient();
MemoryStream oMemoryStream;
try
{
byte[] bytes = oWebClient.DownloadData(sFileVirtualPath);
oMemoryStream = new MemoryStream(bytes);
}
finally
{
oWebClient.Dispose();
}
BinaryReader oBinaryReader = new BinaryReader(oMemoryStream);
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition",
string.Format("attachment;filename={0}", sFileName));
Response.BinaryWrite(oBinaryReader.ReadBytes((int)oMemoryStream.Length));

oBinaryReader.Close();

Response.Flush();
Response.End();
}

To execute this function u can use this code:

protected void Page_Load(object sender, EventArgs e)
{
string sFileVirtualPath = @"http://localhost/TryWebSite/TextFile.txt";
forceDownloadRemoteFile(sFileVirtualPath);
}

No comments: