I need to stream a file which will result in save as prompt in the browser. The issue is, the directory that the file is located is virtually mapped, so I am unable to use Server.MapPath to determine it's actual location. The directory is not in the same location (or even phyical server on the live boxes) as the website.
I'd like something like the following, but that will allow me to pass a web URL, and not a server file path.
I may have to end up building my file path from a config base path, and then append on the rest of the path, but hopefully I can do it this way instead.
var filePath = Server.MapPath(DOCUMENT_PATH);
if (!File.Exists(filePath))
return;
var fileInfo = new System.IO.FileInfo(filePath);
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", String.Format("attachment;filename=\"{0}\"", filePath));
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.WriteFile(filePath);
Response.End();
You could use HttpWebRequest to get the file and stream it back to the client. This allows you to get the file with a url. An example of this that I found ( but can't remember where to give credit ) is
Download url to bytes and convert bytes into stream:
You could try using the DirectoryEntry class with the IIS path prefix:
I do this quite a bit and thought I could add a simpler answer. I set it up as a simple class here, but I run this every evening to collect financial data on companies I'm following.
In this case I pass in a url and it returns the page as HTML. If you want to do something different with the stream instead you can easily change this.
You use it like this:
2 years later, I used Dallas' answer, but I had to change the
HttpWebRequest
toFileWebRequest
since I was linking to direct files. Not sure if this is the case everywhere, but I figured I'd add it. Also, I removedvar resp = Http.Current.Resonse
and just used
Http.Current.Response
in place whereverresp
was referenced.