Beispiel #1
0
        private async Task <IList <ListedItem> > SearchAsync(StorageFolder folder)
        {
            uint index    = 0;
            var  results  = new List <ListedItem>();
            var  stepSize = Math.Min(defaultStepSize, UsedMaxItemCount);
            var  options  = ToQueryOptions();

            var queryResult = folder.CreateItemQueryWithOptions(options);
            var items       = await queryResult.GetItemsAsync(0, stepSize);

            while (items.Count > 0)
            {
                foreach (IStorageItem item in items)
                {
                    try
                    {
                        results.Add(await GetListedItemAsync(item));
                    }
                    catch (Exception ex)
                    {
                        NLog.LogManager.GetCurrentClassLogger().Warn(ex, "Error creating ListedItem from StorageItem");
                    }
                }

                index   += (uint)items.Count;
                stepSize = Math.Min(defaultStepSize, UsedMaxItemCount - (uint)results.Count);
                items    = await queryResult.GetItemsAsync(index, stepSize);
            }
            return(results);
        }
Beispiel #2
0
        private async void Folder_Click(object sender, RoutedEventArgs e)
        {
            FolderPicker picker = new FolderPicker();

            picker.FileTypeFilter.Add("*");
            StorageFolder folder = await picker.PickSingleFolderAsync();

            if (folder != null)
            {
                Stopwatch    sw      = Stopwatch.StartNew();
                QueryOptions options = new QueryOptions();
                options.FolderDepth = FolderDepth.Deep;
                var result = folder.CreateItemQueryWithOptions(options);
                var items  = await result.GetItemsAsync();

                sw.Stop();
                uint count = await result.GetItemCountAsync();

                int pos = folder.Path.Length + 1;
                foreach (var item in items)
                {
                    if (item.IsOfType(StorageItemTypes.File))
                    {
                        Debug.WriteLine(item.Path.Substring(pos));
                    }
                }
                Debug.WriteLine($"DONE in {sw.ElapsedMilliseconds} ms for {count} files");
                Debugger.Break();
            }
        }
Beispiel #3
0
        private async static Task <IReadOnlyList <IStorageItem> > EnumerateFileQuery(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
        {
            // Get a StorageFolder for "path"
            string        fullPath = Path.GetFullPath(path);
            StorageFolder folder   = await StorageFolder.GetFolderFromPathAsync(fullPath).TranslateWinRTTask(fullPath, isDirectory: true);

            // Construct a query for the search.
            QueryOptions query = new QueryOptions();

            // Translate SearchOption into FolderDepth
            query.FolderDepth = searchOption == SearchOption.AllDirectories ? FolderDepth.Deep : FolderDepth.Shallow;

            // Construct an AQS filter
            string normalizedSearchPattern = PathHelpers.NormalizeSearchPattern(searchPattern);

            if (normalizedSearchPattern.Length == 0)
            {
                // An empty searchPattern will return no results and requires no AQS parsing.
                return(new IStorageItem[0]);
            }
            else
            {
                // Parse the query as an ItemPathDisplay filter.
                string searchPath = PathHelpers.GetFullSearchString(fullPath, normalizedSearchPattern);
                string aqs        = "System.ItemPathDisplay:~\"" + searchPath + "\"";
                query.ApplicationSearchFilter = aqs;

                // If the filtered path is deeper than the given user path, we need to get a new folder for it.
                // This occurs when someone does something like Enumerate("C:\first\second\", "C:\first\second\third\*").
                // When AllDirectories is set this isn't an issue, but for TopDirectoryOnly we have to do some special work
                // to make sure something is actually returned when the searchPattern is a subdirectory of the path.
                // To do this, we attempt to get a new StorageFolder for the subdirectory and return an empty enumerable
                // if we can't.
                string searchPatternDirName = Path.GetDirectoryName(normalizedSearchPattern);
                string userPath             = string.IsNullOrEmpty(searchPatternDirName) ? fullPath : Path.Combine(fullPath, searchPatternDirName);
                if (userPath != folder.Path)
                {
                    folder = await StorageFolder.GetFolderFromPathAsync(userPath).TranslateWinRTTask(userPath, isDirectory: true);
                }
            }

            // Execute our built query
            if (searchTarget == SearchTarget.Files)
            {
                StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(query);
                return(await queryResult.GetFilesAsync().TranslateWinRTTask(folder.Path, isDirectory: true));
            }
            else if (searchTarget == SearchTarget.Directories)
            {
                StorageFolderQueryResult queryResult = folder.CreateFolderQueryWithOptions(query);
                return(await queryResult.GetFoldersAsync().TranslateWinRTTask(folder.Path, isDirectory: true));
            }
            else
            {
                StorageItemQueryResult queryResult = folder.CreateItemQueryWithOptions(query);
                return(await queryResult.GetItemsAsync().TranslateWinRTTask(folder.Path, isDirectory: true));
            }
        }
        public override async Task <List <BaseItem> > GetDeletedItemsAsync(FolderAssociation association)
        {
            List <BaseItem> result = new List <BaseItem>();
            //get the storagefolder
            var           localFolderItem = GetAssociatedItem(association.LocalFolderId);
            StorageFolder sFolder         = await StorageFolder.GetFolderFromPathAsync(localFolderItem.EntityId);

            var sItems  = new List <IStorageItem>();
            var options = new QueryOptions();

            options.FolderDepth   = FolderDepth.Deep;
            options.IndexerOption = IndexerOption.UseIndexerWhenAvailable;
            var itemQuery = sFolder.CreateItemQueryWithOptions(options);
            var queryTask = itemQuery.GetItemsAsync();

            //get all the files and folders from the db that were inside the folder at the last time
            var existingItems = ItemTableModel.GetDefault().GetFilesForFolder(association, this.GetType());

            sItems.AddRange(await queryTask);

            var storageItems = new List <BaseItem>();

            foreach (var storageItem in sItems)
            {
                storageItems.Add(new BaseItem {
                    EntityId = storageItem.Path
                });
            }
            var missingItems = existingItems.Except(storageItems, new EnityIdComparer()).ToList();

            //var fixedPath = sFolder.Path.Replace("USERS", "Users");
            foreach (var missingItem in missingItems)
            {
                if (missingItem.EntityId == sFolder.Path)
                {
                    continue;
                }
                //additional check if the file really does not exist
                //for some reason the query seems to return wrong results sometimes
                if (!missingItem.IsCollection)
                {
                    FileInfo fInfo = new FileInfo(missingItem.EntityId);
                    if (!fInfo.Exists)
                    {
                        result.Add(missingItem);
                    }
                }
                else
                {
                    DirectoryInfo dInfo = new DirectoryInfo(missingItem.EntityId);
                    if (!dInfo.Exists)
                    {
                        result.Add(missingItem);
                    }
                }
            }
            return(result);
        }
Beispiel #5
0
        private void initWatching()
        {
            // FilePcker
https:      //social.msdn.microsoft.com/Forums/windowsapps/en-US/8d92a991-a1d5-4d7a-8ca5-36ed15d86d95/uwphow-make-storagefile-from-a-given-string-filepath?forum=wpdevelop

            storageFolder = ApplicationData.Current.LocalFolder;

            queryOptions.FolderDepth = Windows.Storage.Search.FolderDepth.Deep;
            query = storageFolder.CreateItemQueryWithOptions(queryOptions);
        }
Beispiel #6
0
        /// Helpers



        StorageItemQueryResult CreateQuery()
        {
            var fileTypes = new[] { ".pdf", ".jpg", ".jpeg", ".png", ".tiff", ".tif" };
            var options   = new QueryOptions(CommonFileQuery.DefaultQuery, fileTypes);

            options.IndexerOption = IndexerOption.UseIndexerWhenAvailable;
            var query = _monitoredFolder.CreateItemQueryWithOptions(options);

            return(query);
        }
        public async Task <(uint ItemsCount, IAsyncEnumerable <IImageSource> Images)> GetFolderItemsAsync(StorageFolder storageFolder, CancellationToken ct)
        {
#if WINDOWS_UWP
            var query      = storageFolder.CreateItemQueryWithOptions(new QueryOptions(CommonFileQuery.DefaultQuery, SupportedFileTypesHelper.GetAllSupportedFileExtensions()));
            var itemsCount = await query.GetItemCountAsync();

            return(itemsCount, AsyncEnumerableItems(itemsCount, query, ct));
#else
            return (itemsCount, AsyncEnumerableImages(
#endif
        }
Beispiel #8
0
        private static async Task <IList <ListedItem> > SearchWithStorageFolder(string userText, StorageFolder workingDir, bool searchUnindexedItems, int maxItemCount = 10, uint thumbnailSize = 24)
        {
            QueryOptions options = new QueryOptions()
            {
                FolderDepth      = FolderDepth.Deep,
                UserSearchFilter = string.IsNullOrWhiteSpace(userText) ? null : userText,
            };

            if (searchUnindexedItems)
            {
                options.IndexerOption = IndexerOption.DoNotUseIndexer;
            }
            else
            {
                options.IndexerOption = IndexerOption.OnlyUseIndexerAndOptimizeForIndexedProperties;
            }

            options.SortOrder.Clear();
            options.SortOrder.Add(new SortEntry()
            {
                PropertyName   = "System.Search.Rank",
                AscendingOrder = false
            });
            options.SetPropertyPrefetch(Windows.Storage.FileProperties.PropertyPrefetchOptions.None, null);
            options.SetThumbnailPrefetch(Windows.Storage.FileProperties.ThumbnailMode.ListView, 24, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale);
            var  itemQueryResult = workingDir.CreateItemQueryWithOptions(options);
            uint stepSize        = Math.Min(500, (uint)maxItemCount);
            IReadOnlyList <IStorageItem> items = await itemQueryResult.GetItemsAsync(0, stepSize);

            var  returnedItems = new List <ListedItem>();
            uint index         = 0;

            while (items.Count > 0)
            {
                foreach (IStorageItem item in items)
                {
                    try
                    {
                        returnedItems.Add(await GetListedItem(item, thumbnailSize));
                    }
                    catch (Exception ex)
                    {
                        NLog.LogManager.GetCurrentClassLogger().Warn(ex, "Error creating ListedItem from StorageItem");
                    }
                }
                index   += (uint)items.Count;
                stepSize = Math.Min(500, (uint)(maxItemCount - returnedItems.Count));
                items    = await itemQueryResult.GetItemsAsync(index, stepSize);
            }
            return(returnedItems);
        }
        // 排序过滤文件夹和文件
        private async void btnFolderFileOrderFilter_Click(object sender, RoutedEventArgs e)
        {
            lblMsg.Text = "";

            StorageFolder picturesFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.PicturesLibrary);

            // 设置需要过滤的文件的扩展名
            List <string> fileTypeFilter = new List <string>();

            fileTypeFilter.Add(".txt");

            // 创建一个查询参数,可以指定文件的排序方式和文件的类型过滤。文件的各种排序方式请参见 CommonFileQuery 枚举
            QueryOptions query = new QueryOptions(CommonFileQuery.OrderByName, fileTypeFilter);

            // 默认是正序的,如果需要倒序的话可以这样写
            SortEntry se = query.SortOrder[0];

            se.AscendingOrder = false;
            query.SortOrder.RemoveAt(0);
            query.SortOrder.Add(se);

            // 判断一下 picturesFolder 是否支持指定的查询参数
            if (picturesFolder.AreQueryOptionsSupported(query))
            {
                // 创建查询
                StorageItemQueryResult queryResult = picturesFolder.CreateItemQueryWithOptions(query);

                // 执行查询
                IReadOnlyList <IStorageItem> storageItems = await queryResult.GetItemsAsync();

                foreach (IStorageItem storageItem in storageItems)
                {
                    if (storageItem.IsOfType(StorageItemTypes.Folder)) // 是文件夹
                    {
                        StorageFolder storageFolder = storageItem as StorageFolder;
                        lblMsg.Text += "folder: " + storageFolder.Name;
                        lblMsg.Text += Environment.NewLine;
                    }
                    else if (storageItem.IsOfType(StorageItemTypes.File)) // 是文件
                    {
                        StorageFile storageFile = storageItem as StorageFile;
                        lblMsg.Text += "file: " + storageFile.Name;
                        lblMsg.Text += Environment.NewLine;
                    }
                }
            }
        }
        private async void ResetDialog_Loading(FrameworkElement sender, object args)
        {
            StorageFolder SecureFolder = await ApplicationData.Current.LocalCacheFolder.CreateFolderAsync("SecureFolder", CreationCollisionOption.OpenIfExists);

            QueryOptions Options = new QueryOptions
            {
                FolderDepth   = FolderDepth.Shallow,
                IndexerOption = IndexerOption.DoNotUseIndexer
            };

            StorageItemQueryResult ItemQuery = SecureFolder.CreateItemQueryWithOptions(Options);

            uint Count = await ItemQuery.GetItemCountAsync();

            if (Count == 0)
            {
                ClearSecure.IsEnabled = false;
            }

            ClearSecure.Content += $"({Globalization.GetString("Reset_Dialog_TotalFile")}: {Count})";
        }
Beispiel #11
0
        private async Task StartLoadFile()
        {
            IsNewStart = false;

            SecureFolder = await ApplicationData.Current.LocalCacheFolder.CreateFolderAsync("SecureFolder", CreationCollisionOption.OpenIfExists);

            QueryOptions Options = new QueryOptions
            {
                FolderDepth   = FolderDepth.Shallow,
                IndexerOption = IndexerOption.UseIndexerWhenAvailable
            };

            Options.SetThumbnailPrefetch(ThumbnailMode.ListView, 100, ThumbnailOptions.ResizeThumbnail);
            Options.SetPropertyPrefetch(PropertyPrefetchOptions.BasicProperties, new string[] { "System.ItemTypeText", "System.ItemNameDisplayWithoutExtension", "System.FileName", "System.Size", "System.DateModified" });

            StorageItemQueryResult ItemQuery = SecureFolder.CreateItemQueryWithOptions(Options);

            IReadOnlyList <IStorageItem> EncryptedFileList = await ItemQuery.GetItemsAsync(0, 100);

            if (EncryptedFileList.Count == 0)
            {
                EmptyTips.Visibility = Visibility.Visible;
            }

            SecureGridView.Visibility = Visibility.Visible;

            foreach (var Item in EncryptedFileList)
            {
                var Size = await Item.GetSizeRawDataAsync().ConfigureAwait(true);

                var Thumbnail    = new BitmapImage(new Uri("ms-appx:///Assets/LockFile.png"));
                var ModifiedTime = await Item.GetModifiedTimeAsync().ConfigureAwait(true);

                SecureCollection.Add(new FileSystemStorageItemBase(Item as StorageFile, Size, Thumbnail, ModifiedTime));
            }

            await SecureCollection.SetStorageQueryResultAsync(ItemQuery).ConfigureAwait(false);
        }
Beispiel #12
0
        private async Task _GetChangesFromSearchIndex(StorageFolder folder, long associationId,
                                                      List <BaseItem> result)
        {
            var association = FolderAssociationTableModel.GetDefault().GetItem(associationId);
            var files       = new List <IStorageItem>();
            var options     = new QueryOptions();

            options.FolderDepth   = FolderDepth.Deep;
            options.IndexerOption = IndexerOption.UseIndexerWhenAvailable;
            //details about filesystem queries using the indexer
            //https://msdn.microsoft.com/en-us/magazine/mt620012.aspx
            string timeFilter = "System.Search.GatherTime:>=" + association.LastSync;

            options.ApplicationSearchFilter = timeFilter;
            var prefetchedProperties = new List <string> {
                "System.DateModified", "System.Size"
            };

            options.SetPropertyPrefetch(PropertyPrefetchOptions.BasicProperties, prefetchedProperties);
            if (!folder.AreQueryOptionsSupported(options))
            {
                throw new Exception($"Windows Search Index has to be enabled for {folder.Path}");
            }

            var queryResult = folder.CreateItemQueryWithOptions(options);

            queryResult.ApplyNewQueryOptions(options);
            files.AddRange(await queryResult.GetItemsAsync());

            foreach (var file in files)
            {
                try
                {
                    IDictionary <string, object> propertyResult = null;
                    if (file.IsOfType(StorageItemTypes.File))
                    {
                        propertyResult =
                            await((StorageFile)file).Properties.RetrievePropertiesAsync(prefetchedProperties);
                    }
                    else if (file.IsOfType(StorageItemTypes.Folder))
                    {
                        propertyResult =
                            await((StorageFolder)file).Properties.RetrievePropertiesAsync(prefetchedProperties);
                    }
                    var item = new LocalItem(new FolderAssociation {
                        Id = associationId
                    }, file, propertyResult);

                    var existingItem = ItemTableModel.GetDefault().GetItem(item);
                    if (existingItem != null)
                    {
                        if (!item.IsCollection)
                        {
                            //additional check if the file has changed:
                            //even though the size not the best way to make sure if a file has changed
                            //its very unlikely that after a change they have the exact same byte count
                            //so its the best option we have
                            if ((ulong)propertyResult["System.Size"] == existingItem.Size)
                            {
                                continue;
                            }
                        }
                    }
                    result.Add(item);
                }
                catch (Exception)
                {
                    Debug.WriteLine(file);
                    throw;
                }
            }

            if (files.Count == 0)
            {
                await _GetChangedFilesRecursive(folder, association, result);
            }

            if (!IsBackgroundSync)
            {
                var unsynced =
                    ItemTableModel.GetDefault()
                    .GetPostponedItems()
                    .Where(x => x.AdapterType == typeof(FileSystemAdapter));
                foreach (var abstractItem in unsynced)
                {
                    abstractItem.SyncPostponed = false;
                }
                result.AddRange(unsynced);
            }
        }
Beispiel #13
0
        private static async Task <IList <ListedItem> > SearchWithStorageFolder(string userText, StorageFolder workingDir, int maxItemCount = 10)
        {
            QueryOptions options = new QueryOptions()
            {
                FolderDepth      = FolderDepth.Deep,
                UserSearchFilter = string.IsNullOrWhiteSpace(userText) ? null : userText,
            };

            if (App.AppSettings.SearchUnindexedItems)
            {
                options.IndexerOption = IndexerOption.DoNotUseIndexer;
            }
            else
            {
                options.IndexerOption = IndexerOption.OnlyUseIndexerAndOptimizeForIndexedProperties;
            }

            options.SortOrder.Clear();
            options.SortOrder.Add(new SortEntry()
            {
                PropertyName   = "System.Search.Rank",
                AscendingOrder = false
            });
            options.SetPropertyPrefetch(Windows.Storage.FileProperties.PropertyPrefetchOptions.None, null);
            options.SetThumbnailPrefetch(Windows.Storage.FileProperties.ThumbnailMode.ListView, 24, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale);
            var  itemQueryResult = workingDir.CreateItemQueryWithOptions(options);
            uint stepSize        = Math.Min(500, (uint)maxItemCount);
            IReadOnlyList <IStorageItem> items = await itemQueryResult.GetItemsAsync(0, stepSize);

            var  returnedItems = new List <ListedItem>();
            uint index         = 0;

            while (items.Count > 0)
            {
                foreach (IStorageItem item in items)
                {
                    if (item.IsOfType(StorageItemTypes.Folder))
                    {
                        var folder = (StorageFolder)item;
                        returnedItems.Add(new ListedItem(null)
                        {
                            PrimaryItemAttribute      = StorageItemTypes.Folder,
                            ItemName                  = folder.DisplayName,
                            ItemPath                  = folder.Path,
                            LoadFolderGlyph           = true,
                            LoadUnknownTypeGlyph      = false,
                            ItemPropertiesInitialized = true
                        });
                    }
                    else if (item.IsOfType(StorageItemTypes.File))
                    {
                        var file       = (StorageFile)item;
                        var bitmapIcon = new BitmapImage();
                        var thumbnail  = await file.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.ListView, 24, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale);

                        if (thumbnail != null)
                        {
                            await bitmapIcon.SetSourceAsync(thumbnail);

                            returnedItems.Add(new ListedItem(null)
                            {
                                PrimaryItemAttribute      = StorageItemTypes.File,
                                ItemName                  = file.DisplayName,
                                ItemPath                  = file.Path,
                                LoadFileIcon              = true,
                                FileImage                 = bitmapIcon,
                                LoadUnknownTypeGlyph      = false,
                                LoadFolderGlyph           = false,
                                ItemPropertiesInitialized = true
                            });
                        }
                        else
                        {
                            returnedItems.Add(new ListedItem(null)
                            {
                                PrimaryItemAttribute      = StorageItemTypes.File,
                                ItemName                  = file.DisplayName,
                                ItemPath                  = file.Path,
                                LoadFileIcon              = false,
                                LoadUnknownTypeGlyph      = true,
                                LoadFolderGlyph           = false,
                                ItemPropertiesInitialized = true
                            });
                        }
                    }
                }
                index   += (uint)items.Count;
                stepSize = Math.Min(500, (uint)(maxItemCount - returnedItems.Count));
                items    = await itemQueryResult.GetItemsAsync(index, stepSize);
            }
            return(returnedItems);
        }