- Enumerate and query files and folders
- Prerequisites
- Enumerate files and folders in a location
- Query files in a location and enumerate matching files
- Перечисление и запрос файлов и папок Enumerate and query files and folders
- Необходимые компоненты Prerequisites
- Перечисление файлов и папок в расположении Enumerate files and folders in a location
- Запрос файлов в расположении и перечисление соответствующих файлов Query files in a location and enumerate matching files
- The easy way to print a list of folders and files in Windows
- Windows 10 Instructions
- Windows 2012 Server Instructions
- Found this useful? Please share:
- Watch Gary in action
- Reader Interactions
- Comments
Enumerate and query files and folders
Access files and folders in either a folder, library, device, or network location. You can also query the files and folders in a location by constructing file and folder queries.
For guidance on how to store your Universal Windows Platform app’s data, see the ApplicationData class.
В For a complete sample, see the Folder enumeration sample.
Prerequisites
Understand async programming for Universal Windows Platform (UWP) apps
You can learn how to write asynchronous apps in C# or Visual Basic, see Call asynchronous APIs in C# or Visual Basic. To learn how to write asynchronous apps in C++/WinRT, see Concurrency and asynchronous operations with C++/WinRT. To learn how to write asynchronous apps in C++/CX, see Asynchronous programming in C++/CX.
Access permissions to the location
For example, the code in these examples require the picturesLibrary capability, but your location may require a different capability or no capability at all. To learn more, see File access permissions.
Enumerate files and folders in a location
В Remember to declare the picturesLibrary capability.
In this example we first use the StorageFolder.GetFilesAsync method to get all the files in the root folder of the KnownFolders.PicturesLibrary (not in subfolders) and list the name of each file. Next, we use the StorageFolder.GetFoldersAsync method to get all the subfolders in the PicturesLibrary and list the name of each subfolder.
In C# or Visual Basic, remember to put the async keyword in the method declaration of any method in which you use the await operator.
Alternatively, you can use the StorageFolder.GetItemsAsync method to get all items (both files and subfolders) in a particular location. The following example uses the GetItemsAsync method to get all files and subfolders in the root folder of the KnownFolders.PicturesLibrary (not in subfolders). Then the example lists the name of each file and subfolder. If the item is a subfolder, the example appends «folder» to the name.
Query files in a location and enumerate matching files
In this example we query for all the files in the KnownFolders.PicturesLibrary grouped by the month, and this time the example recurses into subfolders. First, we call StorageFolder.CreateFolderQuery and pass the CommonFolderQuery.GroupByMonth value to the method. That gives us a StorageFolderQueryResult object.
Next we call StorageFolderQueryResult.GetFoldersAsync which returns StorageFolder objects representing virtual folders. In this case we’re grouping by month, so the virtual folders each represent a group of files with the same month.
The output of the example looks similar to the following.
Перечисление и запрос файлов и папок Enumerate and query files and folders
Доступ к файлам и папкам в таких расположениях, как папка, библиотека, устройство или расположение в сети. Access files and folders in either a folder, library, device, or network location. Для получения списка файлов и папок из расположения вы также можете создавать запросы файлов и папок. You can also query the files and folders in a location by constructing file and folder queries.
Рекомендации по сохранению данных приложения UWP приведены в классе ApplicationData. For guidance on how to store your Universal Windows Platform app’s data, see the ApplicationData class.
Необходимые компоненты Prerequisites
Общее представление об асинхронном программировании для приложений универсальной платформы Windows (UWP) . Understand async programming for Universal Windows Platform (UWP) apps
Описание процесса написания асинхронных приложений на C# или Visual Basic см. в статье Вызов асинхронных API в C# и Visual Basic. You can learn how to write asynchronous apps in C# or Visual Basic, see Call asynchronous APIs in C# or Visual Basic. Чтобы узнать, как создавать асинхронные приложения с помощью C++/WinRT, ознакомьтесь с разделом Параллельная обработка и асинхронные операции с помощью C++/WinRT. To learn how to write asynchronous apps in C++/WinRT, see Concurrency and asynchronous operations with C++/WinRT. Чтобы узнать, как создавать асинхронные приложения на C++/CX, ознакомьтесь с разделом Асинхронное программирование на языке C++/CX. To learn how to write asynchronous apps in C++/CX, see Asynchronous programming in C++/CX.
Права доступа к расположению Access permissions to the location
Например, коду в этих примерах требуется возможность picturesLibrary. Для вашего расположения может потребоваться другая возможность либо вообще не потребоваться никаких возможностей. For example, the code in these examples require the picturesLibrary capability, but your location may require a different capability or no capability at all. Дополнительную информацию см. в разделе Разрешения на доступ к файлам. To learn more, see File access permissions.
Перечисление файлов и папок в расположении Enumerate files and folders in a location
Обязательно объявите возможность picturesLibrary. Remember to declare the picturesLibrary capability.
В этом примере мы сначала используем метод StorageFolder.GetFilesAsync, чтобы получить все файлы в корневой папке KnownFolders.PicturesLibrary (не во вложенных папках) и перечислить имена всех файлов. In this example we first use the StorageFolder.GetFilesAsync method to get all the files in the root folder of the KnownFolders.PicturesLibrary (not in subfolders) and list the name of each file. Далее мы используем метод StorageFolder.GetFoldersAsync, чтобы получить все папки в PicturesLibrary и перечислить имена всех вложенных папок. Next, we use the StorageFolder.GetFoldersAsync method to get all the subfolders in the PicturesLibrary and list the name of each subfolder.
В языках C# или Visual Basic обязательно вставляйте ключевое слово async в объявления всех методов, в которых используется оператор await. In C# or Visual Basic, remember to put the async keyword in the method declaration of any method in which you use the await operator.
Также вы можете использовать метод StorageFolder.GetItemsAsync, чтобы получить все элементы (как файлы, так и вложенные папки) в определенном расположении. Alternatively, you can use the StorageFolder.GetItemsAsync method to get all items (both files and subfolders) in a particular location. В следующем примере используется метод GetItemsAsync для получения всех файлов и вложенных папок в корневой папке KnownFolders.PicturesLibrary (не во вложенных папках). The following example uses the GetItemsAsync method to get all files and subfolders in the root folder of the KnownFolders.PicturesLibrary (not in subfolders). Затем в примере перечисляются имена всех файлов и вложенных папок. Then the example lists the name of each file and subfolder. Если элемент является вложенной папкой, в примере к имени добавляется «folder» . If the item is a subfolder, the example appends «folder» to the name.
Запрос файлов в расположении и перечисление соответствующих файлов Query files in a location and enumerate matching files
В этом примере мы запрашиваем все файлы в KnownFolders.PicturesLibrary, сгруппированные по месяцам, и в этот раз пример выполняет рекурсию во вложенные папки. In this example we query for all the files in the KnownFolders.PicturesLibrary grouped by the month, and this time the example recurses into subfolders. Сначала мы вызываем StorageFolder.CreateFolderQuery и передаем значение CommonFolderQuery.GroupByMonth в метод. First, we call StorageFolder.CreateFolderQuery and pass the CommonFolderQuery.GroupByMonth value to the method. Благодаря этому получаем объект StorageFolderQueryResult. That gives us a StorageFolderQueryResult object.
Затем мы вызываем StorageFolderQueryResult.GetFoldersAsync, который возвращает объекты класса StorageFolder, представляющие виртуальные папки. Next we call StorageFolderQueryResult.GetFoldersAsync which returns StorageFolder objects representing virtual folders. В этом случае мы группируем по месяцам, поэтому каждая виртуальная папка представляет группу файлов с одинаковым месяцем. In this case we’re grouping by month, so the virtual folders each represent a group of files with the same month.
Результат работы программы выглядит примерно так: The output of the example looks similar to the following.
The easy way to print a list of folders and files in Windows
Windows 10 Instructions
- In Windows Explorer go to the location of the folder which you want to print a contents list.
- Press Alt -> D on your keyboard (the address bar of Windows Explorer will now be in focus).
- Type cmd and press Enter. (the command prompt will open in the path that you chose above).
- Copy and paste the following to the command prompt:
dir > files_and_folders.txt - Press Enter on your keyboard.
In your directory you’ll now have a file called files_and_folders.txt that lists your folders and files.
Windows 2012 Server Instructions
- In Windows Explorer go to the location of the folder which you want to print a contents list.
- Press Shift and alternate mouse click on your folder in Windows Explorer
- Click Open command window here.
- Copy and paste the following to the command prompt:
dir > files_and_folders.txt - Press Enter on your keyboard.
Per the Windows 10 instructions, you’ll now have a file called files_and_folders.txt that lists your folders and files.
Found this useful? Please share:
Watch Gary in action
How to create a lead-capture form with file download.
How to target your most engaged Mailchimp contacts.
Reader Interactions
Comments
Try the freeware program “YourDir”. It is a little quirky (you can only export to a csv. file) but it does the job fairly fast and accurately. I’ve used it since my early XP days and it still works just fine in windows 10. I’ve been able to get a complete listing of files on directory trees with 100,000 files and subdirectories.
excellent tips – thanks!
The Windows 10 advice above worked great and really bailed me out. Somewhat amazing though that you can’t really do this in Windows 10 with a menu option as you might expect. You have to execute an MS/DOS command from the command window to get it done. Wow.
Unworkable unless you know how windos 10 works. I didn’t, so the tipe was useless. Sorry
HAVE THE FILE “FOLDERS AND FILES” BUT IT WOULDN’T OPEN UNTIL I CHOSE “OPEN IN MSWORD.” THANKS FOR THE HELP.
Doesnt work alt D on windows 10
I’m running Windows 10 and Alt-D works for me.
Alt-D wants to delete the folder. Windows 10 here as well.
thanks! this worked for me as well
Is there a way to get the entire tree, including subdirectories and sub-subdirectories?
thank you. im in shock. ive been using windows since like day one and I never knew this. it just shows that you can always learn. its so useful too. really im in shock that I never knew this. im a programmer, have been for over 35 years and it still amazes me that you can learn something new every day. just shows I should read more instruction documents lol thanks mate
I just tried this, but all it gave me was a list of 20 recent files, not a list of all the files in the folder I chose.
Thanks a lot, perfect!
Does not work with UNC Names as cmd does not support UNC naming.
I get “access denied” from one external disk when i hit “all files and folders”
Does not work with UNC Names – just map it as a network drive and it works.
In XP(?) you could print the entire file tree. How can this be done in Windows 10? Other than downloading & using an outside app?
nice tip. Try also “tree /f /a > file.txt” for a nicely formatted tree
Thanks. That was very helpful.
If the methods above are not working, try this:
From the start button, select Windows Accessories
Click on Notepad in the Widows Accessories list to open it.
In Notepad, select File and then select Open.
In the Open dialog box, navigate to the folder whose contents you want to print.
When the folder is selected, a file is displayed called “printit”.
Double-click the printit file.
You can now print or copy the text. 🙂
actually not useless and works the same in windows 7 as it does in windows 10. just follow it thru, have to right click to paste as you cannot ctrl v the entry.
yes! simply add “/s” to include subdirectories, here are a couple options 1) “dir *.*/s>myfile.txt” will give you all directories and files 2) “dir *./s>myfile.txt” for directories only (and other files with no extension, notice there’s no asterisk after the dot). For those who are unfamiliar with doing this in any version of windows, simply run the “Command Prompt” application, from there enter the drive letter you want “O:”, then change to the target directory “CD mystuff\coolfiles”, then you can simply execute the “Dir” command above. I hope this helps.
AhHA! Brilliant! Thank you!
Yes, this works nicely! Displays all subfolders and files.
Great tip for the tree …
Yes, just add “/s” to the command, to indicate you want subdirectories. You might get a large report though!
Rather than going to a DOS cmd prompt, or capturing an printing an image of a directory as other sites advise, use your browser. CMD prompts require exact syntax. This can be a frustrating challenge when directories are deeply nested in the file system. And of course, capturing an image of a directory listing and printing it is not the same as printing an actual list of files in a directory which you might want to modify for presentation: Here is the easiest way to get an editable and printable file listing: In your browser enter: file:///C:/Users/Home/[directoryname]/. Then print it, or copy/paste the HTML page elsewhere.
The tree format is so nice…thanks!
change entry to dir/s > (you can use any text here).txt press enter. It will list the all files from the root.
Alt+D and cmd – if I knew it before! thank you Gary.
what it will do is make the address in the address bad highlight. Then you just type in the cmd and hit enter, and it will open a new window. They probably could have used some illustrations or screen shots to show how to do it. However, if does work with Windows 10.
This worked perfectly in Win 10 instead of “dir > files_and_folders.txt” as written at the top of the page which only seemed to give me the file and folder names in the directory I targeted.
This gave a full file list of everything in the directory and sub directories.
I started programming back when we used BASIC and FORTRAN, so DOS doesn’t frighten me all that much. What I find amazing is the fact that it never occurred to anyone that being able to print out what is essentially a Table of Contents/Index might be a useful thing? Because, having to go through all of this is quite ridiculous.
It’s A List. We live on lists — thrive on list — and we can’t print one?
Here is the EASIEST way to print a listing of your folder:
02. Create a directory named ‘TEMP’ in your C:\dirive if you don’t have one already. Use CAPS in your directory name.
03. Copy and paste this batchfile to the directory of which you want a listing.
04. Highlight the batchfile name and press ‘Enter’.
05. In a flash, the batchfile will complete its task.
06. Navigate to C:\TEMP.
07. A file named ‘directory’ will be there.
08. Open with either Notepad or your favourite wordprocesser.
09. The listing of all the fiiles, including other details, will be there.
/
10. Edit it to your heart’s content and save it as you wish.
I’ve tried all of the suggestions in DOS and get “Access is Denied” each time. How do I allow the system to let me access my own laptop?