Created
September 11, 2023 04:09
-
-
Save admir-live/07e3c462b1401638a68b2bc33d12b9c1 to your computer and use it in GitHub Desktop.
Recursively searches for a file with the specified name within a directory and its subdirectories.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /// <summary> | |
| /// Recursively searches for a file with the specified name within a directory and its subdirectories. | |
| /// </summary> | |
| /// <param name="directoryPath">The path of the directory to start the search from.</param> | |
| /// <param name="fileName">The name of the file to search for.</param> | |
| /// <returns>The full path of the found file or null if the file is not found.</returns> | |
| public static string FindFileInDirectory(string directoryPath, string fileName) | |
| { | |
| if (string.IsNullOrWhiteSpace(directoryPath) || string.IsNullOrWhiteSpace(fileName)) | |
| { | |
| throw new ArgumentException("Directory path and file name must be provided."); | |
| } | |
| if (!Directory.Exists(directoryPath)) | |
| { | |
| throw new DirectoryNotFoundException($"The directory '{directoryPath}' does not exist."); | |
| } | |
| foreach (var file in Directory.GetFiles(directoryPath)) | |
| { | |
| if (Path.GetFileName(file) == fileName) return file; | |
| } | |
| foreach (var subDirectory in Directory.GetDirectories(directoryPath)) | |
| { | |
| string foundFilePath = FindFileInDirectory(subDirectory, fileName); | |
| if (foundFilePath != null) return foundFilePath; | |
| } | |
| return null; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment