在c# MyDocuments中无法获得子目录和文件的任何文件计数

本文关键字:文件 任何 子目录 MyDocuments | 更新日期: 2023-09-27 18:17:22

我使用以下代码尝试计算MyDocuments中的所有目录和文件。

此代码适用于所有其他特殊文件夹(收藏夹,桌面,照片等)

但是当我试图获得'My Documents'的计数时,它失败了。

            /*DOCUMENTS*/               
            documentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            fileCount = Directory.GetFiles(documentsFolder, "*.*", SearchOption.AllDirectories).Length; //THIS IS WHERE IT FAILS - DOES NOT GET PAST HERE
            MessageBox.Show(fileCount.ToString()); //THIS NEVER SHOWS

当我试图获取fileCount时,它失败了-当我在其他目录中获取计数时,它会工作。

这个目录在我的电脑上相当大-所以也许我需要"等待",而它计数?

我不知道为什么它不工作,但所有其他工作都很好,使用基本相同的代码。

在c# MyDocuments中无法获得子目录和文件的任何文件计数

我能想到的唯一方法是从文件计数中排除没有访问权限的文件夹

int fileCount = 0;
var pathToSearch = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//retrieve files
fileCount += Directory.GetFiles(pathToSearch, "*.*", SearchOption.TopDirectoryOnly).Length;
//retrieve folders
foreach (var subFolder in Directory.GetDirectories(pathToSearch, "*.*", SearchOption.TopDirectoryOnly))
{
    try { Array.ForEach(Directory.GetFiles(subFolder, "*.*", SearchOption.AllDirectories), f => fileCount++); }
    catch { }        
}
MessageBox.Show($"{fileCount}");