UWP开发:如何在Documents文件夹中不存在Test文件夹时创建它
Solution for Auto-Creating the Test Folder & Fetching .txt Files in UWP
Got it, let's sort this out for you! The main issue with your original code is that calling CreateFolderAsync("Test") without extra parameters will throw an exception if the folder already exists. We can fix this with a simple collision option that handles both creating the folder (if missing) and opening it (if it's already there) in one line.
Here's the revised, complete code that does exactly what you need:
// Grab the main Documents Library folder var documentsFolder = KnownFolders.DocumentsLibrary; // Create Test folder if it doesn't exist, or open the existing one StorageFolder testFolder = await documentsFolder.CreateFolderAsync( "Test", CreationCollisionOption.OpenIfExists ); // Set up a filter to only target .txt files List<string> fileTypeFilter = new List<string> { ".txt" }; // Configure the query to return files sorted by name QueryOptions queryOptions = new QueryOptions( Windows.Storage.Search.CommonFileQuery.OrderByName, fileTypeFilter ); // Run the query against the Test folder StorageFileQueryResult queryResult = testFolder.CreateFileQueryWithOptions(queryOptions); IReadOnlyList<StorageFile> txtFiles = await queryResult.GetFilesAsync(); // Loop through each file and print its name to debug output foreach (var file in txtFiles) { string fileName = file.Name; Debug.WriteLine(fileName); }
Quick Breakdown of Key Bits:
CreationCollisionOption.OpenIfExists: This is the magic here. It eliminates the need for separate "check if folder exists" logic—just let the system handle both cases without throwing errors.- Sorted File Results: The
CommonFileQuery.OrderByNameensures your .txt files show up in alphabetical order, which matches what you had originally. - Explicit Type for Files: Using
IReadOnlyList<StorageFile>instead of justvarmakes the code clearer, but feel free to stick withvarif you prefer shorter syntax.
Important Checklist:
Don't forget to set up your app's permissions properly, otherwise it won't be able to access the Documents Library:
- Open your
Package.appxmanifestfile. - Add the Documents Library capability:
<Capabilities> <Capability Name="documentsLibrary" /> </Capabilities>
- Also, register the
.txtfile type in the manifest (either via the designer or by adding an extension entry) so your app is allowed to access those files.
内容的提问来源于stack exchange,提问作者Ajay G
相关产品推荐
相关产品推荐

