Programatically Download File from Remote Location to User Through Server (C#)
- 1
- Add a Comment
A while ago, I posted an Entry regarding Programatically Downloading a File from a Remote Location to User Through a Webserver in VB.NET. Today I saw an incoming click from a post on a popular ASP.NET development forum referencing it under the simple title “Download.
A user with over 10,000 forum points named Kaushalparik27 was nice enough to translate the code into C# and link back to me. Isn’t it great when people give credit where credit is due? Now that I’ve given credit, here is the C# version of my original post:
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using System.Data.Sql; using System.Net; using System.IO; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //base.OnLoad(e); string url = string.Empty;// Request.QueryString["DownloadUrl"]; if (url == null || url.Length == 0) { url = "http://img444.imageshack.us/img444/6228/initialgridsq7.jpg"; } //Initialize the input stream HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); int bufferSize = 1; //Initialize the output stream Response.Clear(); Response.AppendHeader("Content-Disposition:", "attachment; filename=download.jpg"); Response.AppendHeader("Content-Length", resp.ContentLength.ToString()); Response.ContentType = "application/download"; //Populate the output stream byte[] ByteBuffer = new byte[bufferSize + 1]; MemoryStream ms = new MemoryStream(ByteBuffer, true); Stream rs = req.GetResponse().GetResponseStream(); byte[] bytes = new byte[bufferSize + 1]; while (rs.Read(ByteBuffer, 0, ByteBuffer.Length) > 0) { Response.BinaryWrite(ms.ToArray()); Response.Flush(); } //Cleanup Response.End(); ms.Close(); ms.Dispose(); rs.Dispose(); ByteBuffer = null; } }

One Comment
mojtaba Vali
May 12th, 2008
at 5:18am
why you don’t use something like this:
#region Downloaduri
public static bool Downloaduri(string uri,string destination, out Exception exception)
{
bool result = false;
try
{
exception = null;
System.Net.WebClient client = new System.Net.WebClient();
client.DownloadFile(uri, destination);
result = true;
}
catch (WebException we)
{
result = false;
exception = we;
}
catch(Exception ex)
{
result = false;
exception = ex;
}
return result;
}
#endregion