James Wilson
James Wilson

Reputation: 5150

Check if file exists not knowing the extension

Is there an easy way to check if a file exists? I know the name of the file just not the extension.

The name of the file will always be their userID from the table.

So for me I could be 1.*

Anything from .jpg, .jpeg, .gif. .png etc for image formats.

Is this easy or should I upload the file extension to the database?

if (System.IO.File.Exists("~/ProfilePictures/" + userID " + ".*"))
   {
   }

Upvotes: 9

Views: 16413

Answers (2)

SmoothRossi
SmoothRossi

Reputation: 41

DirectoryInfo dir = new DirectoryInfo("directory_path");
FileInfo[] files = dir.GetFiles(userID + ".*");
if (files.Length > 0)
{
  //File exists
  foreach (FileInfo file in files)
  {

  }
}
else
{
  //File does not exist
}

Upvotes: 2

Matt Burland
Matt Burland

Reputation: 45135

Use Directory.GetFiles

Something like:

var files = Directory.GetFiles("~/ProfilePictures/",userID + ".*");
if (files.length > 0) 
{
    // at least one matching file exists
    // file name is files[0]
}

Upvotes: 22

Related Questions