Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if file exists not knowing the extension

Tags:

c#

asp.net-mvc

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 " + ".*"))
   {
   }
like image 527
James Wilson Avatar asked Mar 25 '14 17:03

James Wilson


People also ask

How do you check whether a file exists or not?

The exists() function is a part of the File class in Java. This function determines whether the is a file or directory denoted by the abstract filename exists or not. The function returns true if the abstract file path exists or else returns false.

How do I check if a file exists in C++?

To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True .

How do I check if a file exists in XML?

Xml. Use File. Exists(strFilterXMLPath) to determine file's existance.

How do I check if a file exists in HTML?

The exists() method of the File object returns a boolean value based on the existence of the file in which it was invoked. If the file exists, the method returns true. It returns false if the file does not exist.


2 Answers

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]
}
like image 194
Matt Burland Avatar answered Sep 20 '22 06:09

Matt Burland


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
}
like image 23
SmoothRossi Avatar answered Sep 20 '22 06:09

SmoothRossi