Question

I want to take files from a known location on disk and have ASP redirect to them from code-behind, allowing the browser/app/device to control how the content is displayed.

I tried using:

Server.Redirect(pathToFile);

But got the following exception: Invalid path for child request 'C:\ContentFolder\testImage.png'. A virtual path is expected.

How can I allow my site to redirect users to these files? I am storing the base directory in the web config, and the file names are stored in a database.

Was it helpful?

Solution

If the files reside outside of your website directory you can't redirect to them. Think about the security implications if that was possible. You have a few options

  1. Move the files inside the website directory (or a sub-directory of it). Then you can redirect your users to them using a virtual path e.g. Server.Redirect("~/files/somefile.zip").

  2. Set up a virtual directory in IIS that maps to the physical location of the files on disk. Then you can redirect to them using the virtual path. You can do this through the GUI or config file.

  3. Create a HttpHandler that loads the file from disk and returns them in the response. You can use a querystring to identify the file to load e.g. /filehandler.ashx?filename=somefile.zip. A quick google revealed this example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top