Description
Description
I'm trying to retrieve all the files in the documents folder and subfolders in C# .NET 8.0 using Directory.GetFiles . Everytime it throws an error regarding the access not authorized to a subfolder that is the subfolder of the parent directory (e.g. System.UnauthorizedAccessException: 'Access to the path 'C:\Users\user\Documents\My Music' is denied.' where "My Music" is contained in the "user" folder).
Reproduction Steps
string directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string[] files = Directory.GetFiles(directory, "*", SearchOption.AllDirectories);
Expected behavior
List all the folders and subfolders of the current directory without including any other directory not in the path
Actual behavior
List all the folders and subfolders of the current directory, and the folders of the parent with the name of the folder combined with the current path
E.g. C:\Users\user\Documents\My Music is listed when is not in the current folder but in the parent C:\Users\user\My Music
Regression?
No response
Known Workarounds
public class FileSearcher
{
public static List<string> SearchFiles(string rootPath, string searchPattern)
{
List<string> foundFiles = new List<string>();
SearchFilesRecursive(rootPath, searchPattern, foundFiles);
return foundFiles;
}
private static void SearchFilesRecursive(string currentPath, string searchPattern, List<string> foundFiles)
{
// Search for files in the current directory
string[] files = Directory.GetFiles(currentPath, searchPattern);
foundFiles.AddRange(files);
// Get all subdirectories
string[] subdirectories = Directory.GetDirectories(currentPath)
.Where(dir =>
{
try
{
return Directory.Exists(dir) &&
Directory.GetFiles(dir).Length + Directory.GetDirectories(dir).Length > 0;
}
catch (UnauthorizedAccessException)
{
return false;
}
})
.ToArray();
// Recursively search in each subdirectory
foreach (string subdirectory in subdirectories)
{
SearchFilesRecursive(subdirectory, searchPattern, foundFiles);
}
}
}
Configuration
.NET 8.0.204
Windows 11 x64
Other information
The workaround is not perfect, as it excludes also existing folder that the user cannot access because of permissions, cases where I think the UnauthorizedAccessException should be thrown
Activity