You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.OrderByName ensures your .txt files show up in alphabetical order, which matches what you had originally.
  • Explicit Type for Files: Using IReadOnlyList<StorageFile> instead of just var makes the code clearer, but feel free to stick with var if 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:

  1. Open your Package.appxmanifest file.
  2. Add the Documents Library capability:
<Capabilities>
    <Capability Name="documentsLibrary" />
</Capabilities>
  1. Also, register the .txt file 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 12:24:04