开发者

Set image control image dynamically from server side asp.NET

I have a webforms site where users upload files, the file name e开发者_JAVA技巧tc is saved to DB. These files are then displayed in a datalist. I'm trying to get this datalist to show different images (icons) to represent the file types.

This is my code behind. fm.getIcon is a custom function that returns the full file path on the server to the approppriate image which represents the file type.

When i debug the code i can verify that the image does exist at the imgFile path

Private Sub DataList1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles DataList1.ItemDataBound

        Dim docName As Label = e.Item.FindControl("fileNameLabel")
        Dim docImage As Image = e.Item.FindControl("image1")
        Dim imgFile As String = fm.getIcon(My.Computer.FileSystem.GetFileInfo(docName.Text).Extension)
        docImage.ImageUrl = imgFile

End Sub

My problem is that the image is not loading. If i replace imgFile with a hardcoded path to an image it works fine.

What am i missing ?


Please try this.

// 1st Method

string fileLocation = Server.MapPath("~/Images/MyFile.jpg");

FileInfo fileInfo = new FileInfo(fileLocation);

string fileExtension = fileInfo.Extension;

// 2nd Method

System.IO.Path.GetExtension(Server.MapPath("~/Images/MyFile.jpg")); // Result: .jpg

// Your get icon method

docImage.ImageUrl = "~/Icons/" + 
fm.getIcon(Path.GetExtension(Server.MapPath("~/Images/MyFile.jpg")));

public string getIcon(string extension)
{
  switch (extension.ToLower())
  {
    case ".asa":
      return "asa.png";
    case ".asax":
      return "asax.png";
    case ".ascx":
      return "ascx.png";                
    default:
      return "unknown.png";
  }
}


You should confirm that fm.getIcon is actually returning a valid URL for the icon image, not a machine-level file path. You should be able to take the output of fm.getIcon and paste it into a browser and see the image. File permissions could be a issue, the IIS process serving the website needs to be able read the icon image files.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜