Peter Segerblom
Peter Segerblom

Reputation: 2813

Returning image as FileContentResult .net

I'm basicly trying to return a image to the client from a method on the server. It works in all browsers except IE (only tried IE 11 but guessing its the same for older).

Basicly this is what i am doing on the server:

public FileContentResult GetIconForFileExtention(string fileExtention, bool largeIcon = true)
{
    if (!fileExtention.StartsWith("."))
    {
        fileExtention = "." + fileExtention;
    }

    using (IconContainer icon = ShellIcons.GetIconForFile(fileExtention, true, largeIcon))
    {
        Bitmap b = icon.Icon.ToBitmap();             
        MemoryStream ms = new MemoryStream();
        icon.Icon.Save(ms);

        FileContentResult image = null;
        try
        {
            image = File(ms.ToArray(), "image/png", "icon");
        }
        catch (Exception e)
        {
            Elmah.ErrorSignal.FromCurrentContext().Raise(e);
        }

        return image;
     }
}    

This is a .net mvc application. And on the client i just load the image in a img tag like this:

<img src="@Url.Action("GetIconForFileExtention", "MyDocuments", new { fileExtention = "odt" })" />

Any help much appreciated.

Upvotes: 0

Views: 3724

Answers (1)

Faris Zacina
Faris Zacina

Reputation: 14274

I think your action and razor code is correct and I would try checking your GetIconForFile method and making sure it returns correctly the icons.

This is code that should work correctly for populating an icon as a FileContentResult without using the mentioned method:

FileContentResult image = null;

var icon = Icon.ExtractAssociatedIcon(Server.MapPath("~") + "/favicon.ico");

using (var ms = new MemoryStream())
{
    icon.Save(ms);
    image = File(ms.ToArray(), "image/png", "icon");
}

return image;

You can try to run it and confirm the issue is not in the Action and in the Razor view, but in the ShellIcons class. Before running it make sure you have a "favicon.ico" in your root folder ;)

Upvotes: 1

Related Questions