Last post Apr 27, 2016 03:54 AM by navneetmitawa
Apr 26, 2016 01:18 PM|Gautam Sharma|LINK
I have a product page, where I display the product image by referring the image located in a folder called "Images/Products/1212"..
This folder has several images like Image1.jpg, Image2.jpg, Image3.png
for each product, I would to show the first image. I am using the below code,
var productFolderContents = new DirectoryInfo(Server.MapPath("~/Images/Products/" + product.Sku + "/Thumb"));
<img src="~/Images/Products/@product.Sku/Thumb/@productFolderContents.GetFiles()" class="img-responsive" alt="@product.Name" />
The above code works...
Can I shorten the above code or is there any efficient way? I feel the above is not so efficient
Apr 26, 2016 02:00 PM|Nataraj Gandhi Arunachalam|LINK
Maybe instead of getting all the files and looking at the  item, if your images have some meaningful name such as productname_1 etc or image1 etc, why not just directly use the image name with you products location in your src.
Apr 26, 2016 03:01 PM|Gautam Sharma|LINK
The first file can be of any extension, jpeg, jpg or png..
Apr 26, 2016 03:20 PM|Gautam Sharma|LINK
or this one is better
var imagePath = Server.MapPath("~/Images/Products/" + product.Sku + "/Thumb");
var imageName = Path.GetFileName(Directory.GetFiles(imagePath));
<img src="~/Images/Products/@product.Sku/Thumb/@imageName" class="img-responsive" alt="@product.Name" />
Apr 27, 2016 03:45 AM|Nataraj Gandhi Arunachalam|LINK
I guess it should be fine as long as your folder is not having tons of files. In anycase, I believe the GetFiles() method must be pretty much optimized for you to see any performance hit.
Apr 27, 2016 03:54 AM|navneetmitawa|LINK
The following will do the trick if you want one file.
var file = Directory.GetFiles("C:\\First\\Second\\").FirstOrDefault();
if (file != null)
var fileName = Path.GetFileName(file);
The following will get you all the file names:
var files = Directory.GetFiles("C:\\First\\Second\\");
var fileNames = files.Select(f => Path.GetFileName(f));