twal
twal

Reputation: 7039

ASP.NET MVC images from a virtual Path

I have an application that needs to get images that will not be part of the application it's self. But stored on the file System. I have been told the best way to get this is to use a virtual directory rather than getting them staight off the file system like this

 public FilestreamResult GetPicture(string Filename) { 
    Filename = @"C:\SomePath\" + Filename;
        return new FileStreamResult(new FileStream(Filename, FileMode.Open, FileAccess.Read, FileShare.Read), "image/jpeg"));
}

Is it true using a virtual directory is the way to go instead of using the file path? The next question is how do I create this virtual directory and how do I get the image from the virtual directory?

Thank you!

Upvotes: 0

Views: 4242

Answers (3)

Michael Gattuso
Michael Gattuso

Reputation: 13200

Using the method in your post has a bunch of overhead (all images pass through the .net application stack). If you plan on securing access to the images or need some other application level control then this can acceptable but if these are standard asset files then you will want to use a virtual directory.

You configure a virtual directory in IIS by right clicking the web site and selecting new virtual directory. You will give this directory a name such as "content" and then point it to your picture location (c:\somepath). You will then access the directory via http://yourwebsite.com/content/filename.jpg and it will appear as a part of your site.

Upvotes: 1

xandy
xandy

Reputation: 27411

I am not sure what virtual directory means by you. But I don't think pulling files directly from File System is always a bad idea. It is simple and you don't have to worry about the Directory structure (which sometimes quite troublesome to 'simulate').

Since you mentioned asp.net, I would recommend you that instead of hardcoding the root of your storage, you can pull that out to web.config file.

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190942

Use Server.MapPath("~/someimage.jpg").

See: http://msdn.microsoft.com/en-us/library/ms524632(VS.90).aspx

Upvotes: 1

Related Questions