简体   繁体   中英

How to get relative path of image for src attribute

I want to display list of images on my asp.net web page. The pictures are located in folder. My aspx code looks like this

   <asp:ListView runat="server" ID="lvPicturePaths">
   <ItemTemplate>
     <img src="<%# Container.DataItem %>" />
   </ItemTemplate>
    </ListView>

In code behind I have:

  private void GetImagePaths()
   {
      List<string> pathForPictures=new List<string>();
    var path=Server.MapPath("~/images/");
  foreach(var PP in Directory.GetFiles(path))
    {
    pathForPictures.Add(PP);
    }
    lvPicturePaths.DataSource=pathForPictures;
    lvPicturePath.DataBind();
 }

The problem is that src attribute of the img tag need relative path, something like localhost/images... Now I get something like: C:\\Inetpub\\wwwroot\\images\\image1.jpg

You can use:

pathForPictures.Add(
    Page.ResolveClientUrl(
        System.IO.Path.Combine(
            "~/images/",
            System.IO.Path.GetFileName(PP)
        )
    )
);

Or instead of doing a loop:

private void GetImagePaths()
{
    const string path = "~/images/";
    var pictures =
        Directory.GetFiles(Server.MapPath(path))
            .Select(p => 
                Page.ResolveClientUrl(Path.Combine(path, Path.GetFileName(p))));
    lvPicturePaths.DataSource = pictures;
    lvPicturePath.DataBind();
}

尝试使用Page.ResolveUrl而不是Server.MapPath

Use ResolveUrl

Try this code

this.ResolveUrl("~/images/")

instead of

Server.MapPath("~/images/");

or simply try ResolveUrl("~/images/")

More details , see this good explanation for Path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM