KeyLimeTie Blog

Hide your file downloads with binary streaming (C#)

By Brian Pautsch – 3/9/2006 10:19:38 PM. Posted to Code Snippets.

Ever have the need to allow people to download files but don't want them to know the physical location? It's actually pretty easy...just put your files in a location not accessible to the web and stream them back to the user:

1private void SendFileToUser(string strFileFullPath)
2{
3 FileStream objFile = null;
4 BinaryReader objBR = null;
5 try 
6 { 
7  objFile = new FileStream(strFileFullPath, FileMode.Open); 
8  //Clear and change the response headers
9  Response.Clear();
10  Response.Charset = "";
11  Response.AddHeader("Content-disposition", 
12   "attachment; filename=" + 
13   Path.GetFileName(strFileFullPath));
14  //Stream the file down
15  objBR = new BinaryReader(objFile);
16  for (long l = 0; l < objFile.Length; l++)
17  {
18   Response.OutputStream.WriteByte(objBR.ReadByte());
19  }
20  objBR.Close();
21 }
22 catch (Exception ex)
23 {
24  throw new Exception("Exception: " + ex.Message);
25 }
26 finally
27 {
28  objBR = null;
29  objFile = null;
30 }
31}

Comments

On 1/8/2010 Anderson Schmitt said:
(sorry for the bad english)

Leave a Comment

Name:
Email:
URL:
Comment:
Security Code:
Type Security Code:

Photos on Flickr

More Photos »

Search Blog


Get Email Updates

Like what you read here at KeyLimeTie? Sign up for our email list!

Subscribe