How to check the filenames in a folder
I would like to be able to iterate over the names of some image files in a folder using C #. So, for intance, I have a folder named image and contains the following images
image dog.jpg cat.jpg horse.jpg
I want to be able to view names and be able to say
if(filename == dog.jpg)
return true
else
return false
Something like that
thank
source to share
You must use a static method Exists
on System.IO.File
.
return System.IO.File.Exists("dog.jpg")
Because the method returns a Boolean value, there is no need for an expression in the example in the example if
.
You can also use a bit of Linq magic to determine if a file exists in a folder structure like:
var dir = new System.IO.DirectoryInfo(startFolder);
var fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
bool fileExists = fileList.Any(f => f.FullName == "dog.jpg");
or even shorter:
return System.IO.Directory
.GetFiles(@"c:\myfolder", "dog.jpg", SearchOption.AllDirectories)
.Any();
which will search for the specified folder and the entire subfolder with the "dog.jpg" template. The extension method Any()
just checks if it contains IEnumerable
all the elements. I think this is the most efficient way to do it (based on gut feeling).
source to share
From http://weblogs.asp.net/israelio/archive/2004/06/23/162913.aspx Just paste your if in the "// do something with filename" area:
// How much deep to scan. (of course you can also pass it to the method)
const int HowDeepToScan=4;
public static void ProcessDir(string sourceDir, int recursionLvl)
{
if (recursionLvl<=HowDeepToScan)
{
// Process the list of files found in the directory.
string [] fileEntries = Directory.GetFiles(sourceDir);
foreach(string fileName in fileEntries)
{
// do something with fileName
Console.WriteLine(fileName);
}
// Recurse into subdirectories of this directory.
string [] subdirEntries = Directory.GetDirectories(sourceDir);
foreach(string subdir in subdirEntries)
// Do not iterate through reparse points
if ((File.GetAttributes(subdir) &
FileAttributes.ReparsePoint) !=
FileAttributes.ReparsePoint)
ProcessDir(subdir,recursionLvl+1);
}
}
source to share