Displaying images in your ASP.Net IIS website from another hard drive.

I recently ran into an issue with attempting to display user uploaded images in my ASP.Net website. These images are uploaded and stored on another drive with a lot more room on it. Browsers like Chrome block displaying images from anywhere that is outside the IIS directory for security reasons, which is good.

All I had to do was create another webpage that wrote the binary of the image file as a response and use that link as the image source.

The frontend page for reading the image should be blank. Lets call the page displaying the image ImageDisplayer and the page reading the image ImageReader.

ImageDisplayer

Frontend .aspx file:

<asp:Image ID="ImageToDisplay" Width="100%" runat="server" />

Backend .aspx.cs file:

ImageToDisplay.ImageUrl = "<URL_To_New_Page>?id=<ID_For_The_Image>";

ImageReader

Frontend .aspx file:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ImageReader.aspx.cs" Inherits="Website.ImageReader" %>

That's all there is for the frontend, no extra HTML code.

Backend .aspx.cs file:

using (FileStream fs = File.Open($"<Location_Of_The_Image_File>/{Request.QueryString["id"]}.jpg", FileMode.Open))
{
    byte[] bytes = new byte[fs.Length];
    fs.Read(bytes, 0, bytes.Length);
    fs.Close();
    Response.BinaryWrite(bytes);
}

That's it! The image will now be displayed regardless of where the file is.

Of course you should add things like error handling and security if the images could be sensitive, like checking if the user is authenticated.

0
Subscribe to my newsletter

Read articles from Shayne Kiekebosch directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shayne Kiekebosch
Shayne Kiekebosch

.NET developer specialising in Windows Mixed Reality and Windows forms/services. Utilising Unity I have developed applications for the Microsoft HoloLens 1 and 2 and the Meta Quest 1, 2 and Pro. I was also a senior dev at Blackout Games working on their Rugby Management Game.