Check if File exists in directory ignoring the extension

I am using .NET 2.0 and Linq is out of question. I would like to check if file exists inside a directory without knowledge of the file extension.

I just need this logic done.

1.Check File exists in Directory using String Filename provided using search pattern leaving out the extension of the File

2.Get the Files if they exists and Databind to provide Download links.If file does not exist then start uploading the File.

Update:
Directory.GetFiles() and DirectoryInfo.GetFiles() indeed solves the part where in i check for File existence. As for the performance regarding FileInfo objects, these were only solution to my requirements of databinding to provide download links

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

DirectoryInfo root = new DirectoryInfo("your_directory_path");
FileInfo[] listfiles = root.GetFiles("dummy.*");
if (listfiles.Length > 0)
{
  //File exists
  foreach (FileInfo file in listfiles)
        {
            //Get Filename and link download here
        }
}
else
{
  //File does not exist
  //Upload
}

Hope this works

Method 2

To see if a file exists with that name, can you not just use..

However, Directory.GetFiles already includes the full path

string [] files = Directory.GetFiles(Path,"name*");
bool exists =  files.Length > 0;

if ( exists)
{
   //Get file info - assuming only one file here..
    FileInfo fi = new FileInfo(files[0]);

    //Or loop through all files
    foreach (string s in files)
    {
         FileInfo fi = new FileInfo(s);
         //Do something with fileinfo
    }
}

Method 3

You can use DirectoryInfo.GetFiles() to have a FileInfo[] instead of a String[].


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x