SoFunction
Updated on 2025-03-06

C# Example method to obtain all pictures or other file names in a specified format in a folder

1. Write a subfunction to get file name (full path)

/////param
///path: folder path///suffix: Suffix format, such as bmp, txt///fileList:Storage the file name///isSubcatalog:true traverses subfolders, otherwise it will not traversevoid getFiles(string path, string suffix, ref List<string> fileList, bool isSubcatalog)
{
string filename;
DirectoryInfo dir = new DirectoryInfo(path);
FileInfo[] file = ();
//DirectoryInfo[] dii = ();//If you need to traverse subfolders, you need to use itforeach (FileInfo f in file)
{
filename = ;
if ((suffix))//Judge file suffix and get the file in the specified format full path to add to fileList{
(filename);
}
}
Get the list of files in the subfolder,Recursive traversal 
  if(isSubcatalog)
  {
    foreach (DirectoryInfo d in dii)
    {
    getFiles(, fileList);
    }
  }

return;
}

2. Place a button control in the interface, and the folder path selection window pops up when clicking the button, and call the getFiles subfunction:

List<string> imageFiles = new List<string>();
private void btnSelectPath_Click(object sender, EventArgs e)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
 = "Please choose image path.";
DialogResult result = ();
if (result == )
{
return;
}
string folderPath = ();
DirectoryInfo theFolder = new DirectoryInfo(folderPath);
if ()
{
getFiles(folderPath,"bmp", ref imageFiles, false);
return; 
}
}

You can test the above example code locally. Thank you for your learning and support.