views:

381

answers:

2

I am building an asp.net website. I want to show image on the page, but while I know the image name, I don't know the extension.

So, I want to open the images directory and get the image by its name whatever its extension.

+2  A: 

That's not really how files work -- you need to know the whole name. For example, what happens if there's multiple images with the same base name and different extensions? Compare foo.png and foo.jpg, for example.

One suggestion is to try doing a wildcard search on all files with some base name in that directory (that's what bstoney's solution does; see here). If you find exactly one match, you're done. If you get multiple matches, you'll need to make rules about which one wins.

John Feminella
+7  A: 

You can use the Directory object to get a list of file in a directory

string imageFilename = System.IO.Directory.GetFiles( imageDirectory, name + ".*" ).First();
bstoney
It's pretty much a matter of taste, but I'd rather use ' name + ".*" ' in stead of concat function. Same end result, but more readable.
DJ Pirtu
It gave me this error: "System.ArgumentException: Illegal characters in path."
Amr ElGarhy
"System.ArgumentException: Illegal characters in path." occurs when you haven't escaped the '\' character try "C:\\" or @"C:\"
bstoney
DJ Pirtu, string.Concat is a habit, our work coding style requires it.
bstoney