1

I have an aspx page that I am displaying image from codehind c#. Every item has it's own directory with images inside if there were any uploaded. It works fine except if the directory doesn't exist for a certain item, I get a return error "Could not find part of the path.... In some cases the directory will not exist because there are no images assigned to the item. What should I include in my code to ignore this if there is no directory for the item?

Below is the code used to display the images:

string[] filePaths = Directory.GetFiles(Server.MapPath("/Test/Files/Item" + ItemNumber + "/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
string fileName = Path.GetFileName(filePath);
files.Add(new ListItem(fileName, "/Test/Files/Item" + ItemNumber + "/" + fileName));
}
Dr.Prog
  • 229
  • 3
  • 13

1 Answers1

2

Use File.Exists method to filter out image files that are missing:

foreach (string filePath in filePaths.Where(File.Exists)) {
    ... //
}

You need to add using System.Linq and using System.IO in order for the above to compile.

Note: The above uses method groups for creating lambda expressions. Where(File.Exists) is a shorthand syntax for Where(f => File.Exists(f))

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523