简体   繁体   中英

How to store images in a list from image folder and passing it to image src in (asp.net| vb.net)

I have got two image folders namely a and b which consist of images of products. All images are save as there productid. how can can i find the images from a folder by passing there productid and save the images in a list.

Dim AllImages As New List(Of String)

After saving it , how can i render those images one by one into string builder like

Dim imagecontainer As New StringBuilder
 For Each image In AllImages
imagecontainer.Append("<img src="image" alt="" />") Next image

Any ideas of how to do this, your help will be highly appreciated.

You can use the ResolveClientUrl within your page code-behind:


var clientImageUrl = ResolveClientUrl("yourimagefolder/sampleimage.jpg");

Or you can use VirtualPathUtility.ToAbsolute that will return the same result :


VirtualPathUtility.ToAbsolute("yourimagefolder/sampleimage.jpg")

In order to read all the files from a folder and then filter them by file name (your ID) you can use (use the System.IO namespace) :


 DirectoryInfo directory = new System.IO.DirectoryInfo("c:\YourFolder");
 var allFiles = directory.GetFiles(".", System.IO.SearchOption.AllDirectories);
var fileFounds = from file in allFiles where file.Name == "YourID" select file;

foreach (var file in fileFounds) { //Build your image }

EDIT : here's the vb.net version (I've used a code converter, hope it worked well: )


'Using ResolveClientUrl 
Dim clientImageUrl = ResolveClientUrl("yourimagefolder/sampleimage.jpg")

'Using VirtualPathUtility VirtualPathUtility.ToAbsolute("yourimagefolder/sampleimage.jpg")

'Reading files from directory Dim directory As DirectoryInfo = New System.IO.DirectoryInfo("c:\YourFolder") Dim allFiles = directory.GetFiles(".", System.IO.SearchOption.AllDirectories)

Dim fileFounds = _ Where file.Name = "YourID"

    'Build your image

For Each file As var In fileFounds Next

  • Use DirectoryInfo to get all files in a directory
  • Use your foreach loop to build the html
  • Add a PlaceHolder to your page and add your html to it

Or, you could use a Repeater bound to a list of image path strings. This will give you much more control over your markup.

Here's an example with a Repeater.

Markup:

<asp:Repeater id="imageRepeater" runat="server">
  <ItemTemplate>
     <img src='<%# Container.DataItem %>' alt="" />
  </ItemTemplate>
</asp:Repeater>

Codebehind:

imageRepeater.DataSource = imageFiles
imageRepeater.DataBind()

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