Benny Sutton is 4 hire - just click here

Deliver file downloads anonymously C#

When you deliver digital content from your server you do not want to reveal the source location because malign users can exploit this to download further content

One solution to anonymize source location is to package the files that they use is authorised to download inside a zip file

The other solution, which I detail here, is to deliver the code as a stream with HttpContext.Response

             
                    // derive the path to the file you will deliver 
                    // here we know the folder and get the FileName for the db record
                    String path = Server.MapPath("~/downloads/" + download.FileName.ToLower()); // the ToLower is needed
                    if (System.IO.File.Exists(path)) // check file exists
                    {
                        // only deliver .zip .wav or .mp3 files 
                        if (Path.GetExtension(path) == ".zip")
                        {
                            HttpContext.Response.ContentType = "application/zip";
                            HttpContext.Response.AppendHeader("Content-Disposition", "attachment; filename=" + System.IO.Path.GetFileName(path).Replace(" ", "_")); // the replace _ is needed!
                            HttpContext.Response.TransmitFile(path);
                        }
                        else if (Path.GetExtension(path) == ".mp3")
                        {
                            HttpContext.Response.ContentType = "Application/mp3";
                            HttpContext.Response.AppendHeader("Content-Disposition", "attachment; filename=" + System.IO.Path.GetFileName(path).Replace(" ", "_"));
                            HttpContext.Response.TransmitFile(path);
                        }
                        else if (Path.GetExtension(path) == ".wav")
                        {
                            HttpContext.Response.ContentType = "audio/x-wav";
                            HttpContext.Response.AppendHeader("Content-Disposition", "attachment; filename=" + System.IO.Path.GetFileName(path).Replace(" ", "_"));
                            HttpContext.Response.TransmitFile(path);
                        }
                        else
                        {
                            ViewBag.Message = "This is not a zip, wav or mp3 file: " + download.Name;
                            return View();
                        }
                    }
                    else
                    {
                        ViewBag.Message = " File does not exist: " + download.Name;
                        return View();
                    };