Tuesday, September 25, 2018

Get all of the names of all of the files in a directory with C#.

An example and a pratical application:

public void DeleteOldLogsToAvoidMemoryLeaks(Bootstrapping bootstrapping)
{
   foreach (string filePath in Directory.GetFiles(bootstrapping.LogDirectory))
   {
      string[] filePathParts = filePath.Split('\\');
      string fileName = filePathParts[filePathParts.Length - 1];
      if (fileName.Length > 3)
      {
         string fileNamePrefix = "" + fileName[0] + fileName[1] + fileName[2] + fileName[3];
         if (fileNamePrefix != bootstrapping.Timekeeping.GetDate().Year.ToString())
         {
            string[] fileNameParts = fileName.Split('.');
            string extension = fileNameParts[fileNameParts.Length - 1];
            if (extension == "txt")
            {
               File.Delete(filePath);
            }
         }
      }
   }
}

 
 

I got the name from this which also suggests that there is a Directory.GetDirectories beyond Directory.GetFiles and that one may use the strings from Directory.GetDirectories to turn around and crawl for file names one folder deep with Directory.GetFiles and getting creative a bit one may thus recursively make a list of all files in all folders from a topmost folder downward.

No comments:

Post a Comment