UWP 应用创建的文件未在 Windows 10 1803 中编制索引



在我的UWP应用中,我正在创建应由Windows索引编制索引的文件,以便以后可以使用全文搜索找到它们。

public async Task TestFullTextSearch()
{
StorageFolder folder = ApplicationData.Current.LocalCacheFolder;
CreateFile(folder.Path + Path.DirectorySeparatorChar + "myDocument.txt", "Some text 123");
await Task.Delay(5000); // to ensure that the file is already index before querying
int numberOfResults = await SearchForResults(folder, "*");
// numberOfResults is 1 in Windows 10, 1709 and 0 in 1803
}
public void CreateFile(string path, string text)
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(text);
}
}
private async Task<int> SearchForResults(StorageFolder folder, string searchString)
{
QueryOptions queryOptions = new QueryOptions(CommonFileQuery.OrderBySearchRank, new List<string>() { "*" });
queryOptions.UserSearchFilter = searchString;
StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(queryOptions);
IReadOnlyList<StorageFile> files = await queryResult.GetFilesAsync();
return files.Count;
}

在上面的示例中,在 Windows 10、1709 下执行代码时,numberOfResults为 1。在 Windows 10、1803 下执行相同的代码时,numberOfResults为 0。

在这两种情况下,位置都会添加到Windows索引中(通过"索引选项"添加(。

我检查了权限,它们看起来完全相同。我还尝试在相应的文件夹中手动创建一个文件并使用 Windows 资源管理器的 windows 搜索,它显示 0 个结果(在 1803 下,在 1709 下,结果按预期显示(。在少数情况下,创建的文件最终出现在查询中并且可以搜索,我不知道为什么。

我在 3 台不同的 Windows 10、1803 机器下尝试了这个,结果完全相同(在几台 1709 机器上,这里工作正常(。

我自己找到了解决方案: 在"LocalCache"和"LocalState"(可能还有其他应用文件夹(中,名为"Indexed"的文件夹会自动添加到Windows搜索索引中。该文件夹必须直接在"LocalCache"或"LocalState"文件夹下创建。

因此,通过创建一个名为"索引"的文件夹并将文件/文件夹放入该文件夹,文件将被索引。

请参阅下面的工作代码(现在适用于 Windows 10、1709 和 1803(。我只更改了第一行来创建"索引"文件夹。

public async Task TestFullTextSearch()
{
StorageFolder folder = await ApplicationData.Current.LocalCacheFolder.CreateFolderAsync("Indexed", CreationCollisionOption.OpenIfExists);
CreateFile(folder.Path + Path.DirectorySeparatorChar + "myDocument.txt", "Some text 123");
await Task.Delay(5000); // to ensure that the file is already index before querying
int numberOfResults = await SearchForResults(folder, "*");
// numberOfResults is 1 in Windows 10, 1709 and 1 in 1803
}
public void CreateFile(string path, string text)
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(text);
}
}
private async Task<int> SearchForResults(StorageFolder folder, string searchString)
{
QueryOptions queryOptions = new QueryOptions(CommonFileQuery.OrderBySearchRank, new List<string>() { "*" });
queryOptions.UserSearchFilter = searchString;
StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(queryOptions);
IReadOnlyList<StorageFile> files = await queryResult.GetFilesAsync();
return files.Count;
}

要检查"已编入索引"文件夹是否确实已编入索引,请转到索引选项。始终选中"索引"文件夹,并且无法删除复选标记。

资料来源:https://learn.microsoft.com/en-us/uwp/api/windows.storage.applicationdata.localfolder

最新更新