Ejemplo n.º 1
0
        public async Task <List <FileSystemStorageItemBase> > GetChildItemsAsync(bool IncludeHiddenItems, ItemFilters Filter = ItemFilters.File | ItemFilters.Folder)
        {
            if (WIN_Native_API.CheckLocationAvailability(Path))
            {
                return(WIN_Native_API.GetStorageItems(Path, IncludeHiddenItems, Filter));
            }
            else
            {
                LogTracer.Log($"Native API could not enum subitems in path: \"{Path}\", fall back to UWP storage API");

                try
                {
                    if (await GetStorageItemAsync().ConfigureAwait(true) is StorageFolder Folder)
                    {
                        QueryOptions Options = new QueryOptions
                        {
                            FolderDepth   = FolderDepth.Shallow,
                            IndexerOption = IndexerOption.UseIndexerWhenAvailable
                        };
                        Options.SetThumbnailPrefetch(Windows.Storage.FileProperties.ThumbnailMode.ListView, 150, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale);
                        Options.SetPropertyPrefetch(Windows.Storage.FileProperties.PropertyPrefetchOptions.BasicProperties, new string[] { "System.Size", "System.DateModified" });

                        StorageItemQueryResult Query = Folder.CreateItemQueryWithOptions(Options);

                        uint Count = await Query.GetItemCountAsync();

                        List <FileSystemStorageItemBase> Result = new List <FileSystemStorageItemBase>(Convert.ToInt32(Count));

                        for (uint i = 0; i < Count; i += 30)
                        {
                            IReadOnlyList <IStorageItem> CurrentList = await Query.GetItemsAsync(i, 30);

                            foreach (IStorageItem Item in CurrentList.Where((Item) => (Item.IsOfType(StorageItemTypes.Folder) && Filter.HasFlag(ItemFilters.Folder)) || (Item.IsOfType(StorageItemTypes.File) && Filter.HasFlag(ItemFilters.File))))
                            {
                                if (Item is StorageFolder SubFolder)
                                {
                                    Result.Add(new FileSystemStorageFolder(SubFolder, await SubFolder.GetThumbnailBitmapAsync().ConfigureAwait(true), await SubFolder.GetModifiedTimeAsync().ConfigureAwait(true)));
                                }
                                else if (Item is StorageFile SubFile)
                                {
                                    Result.Add(new FileSystemStorageFile(SubFile, await SubFile.GetThumbnailBitmapAsync().ConfigureAwait(true), await SubFile.GetSizeRawDataAsync().ConfigureAwait(true), await SubFile.GetModifiedTimeAsync().ConfigureAwait(true)));
                                }
                            }
                        }

                        return(Result);
                    }
                    else
                    {
                        return(new List <FileSystemStorageItemBase>(0));
                    }
                }
                catch
                {
                    LogTracer.Log($"UWP API could not enum subitems in path: \"{Path}\"");
                    return(new List <FileSystemStorageItemBase>(0));
                }
            }
        }
Ejemplo n.º 2
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));
            }
        }
Ejemplo n.º 3
0
 public LocalFolderViewModel(StorageFolder folder, PathModel parentPathModel)
 {
     CurrentFolder = folder;
     Path          = new PathModel(folder.DisplayName, folder.Path)
     {
         Parent = parentPathModel
     };
     _query = CurrentFolder.CreateItemQuery();
 }
Ejemplo n.º 4
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.Parameter is Tuple <FileControl, StorageItemQueryResult> Parameters)
            {
                FileControlInstance = Parameters.Item1;
                ItemQuery           = Parameters.Item2;

                CommonAccessCollection.Register(FileControlInstance, this);

                await Initialize().ConfigureAwait(false);
            }
        }
Ejemplo n.º 5
0
        // 排序过滤文件夹和文件
        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;
                    }
                }
            }
        }
        public async Task SetStorageQueryResultAsync(StorageItemQueryResult InputQuery)
        {
            if (InputQuery == null)
            {
                throw new ArgumentNullException(nameof(InputQuery), "Parameter could not be null");
            }

            ItemQuery = InputQuery;

            MaxNum = await ItemQuery.GetItemCountAsync();

            CurrentIndex = MaxNum > 100 ? 100 : MaxNum;

            if (MaxNum > 100)
            {
                HasMoreItems = true;
            }
        }
Ejemplo n.º 7
0
        public static async IAsyncEnumerable <IStorageItem> GetEnumerator(StorageItemQueryResult query, uint itemsCount, [EnumeratorCancellation] CancellationToken ct = default)
        {
            uint currentCount = 0;

            while (currentCount < itemsCount)
            {
                ct.ThrowIfCancellationRequested();

                var items = await query.GetItemsAsync(currentCount, GetEnumeratorOneTimeGetCount).AsTask(ct);

                foreach (var item in items)
                {
                    yield return(item);
                }

                currentCount += (uint)items.Count;
            }
        }
Ejemplo n.º 8
0
        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})";
        }
Ejemplo n.º 9
0
        //public IAsyncOperation<StorageFolder> UpdateQueueList()
        //{
        //    files = Windows.Storage.StorageFolder.GetFolderFromPathAsync(pathToMusic);
        //    return files;

        //    // To avoid permission errors for now the 15063 is the suggested lowest version
        //}

        public async void GetFilesInFolder()
        {
            List <IStorageItem> filesInFolder = new List <IStorageItem>();

            // Get the app's installation folder.
            StorageFolder appFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

            // Get the items in the current folder.
            StorageItemQueryResult itemsInFolder = KnownFolders.MusicLibrary.CreateItemQuery();

            // Iterate over the results and print the list of items
            // to the Visual Studio Output window.
            foreach (IStorageItem item in await itemsInFolder.GetItemsAsync())
            {
                // Adding all the files to the variable
                if (item.IsOfType(StorageItemTypes.File))
                {
                    filesInFolder.Add(item);
                }
            }
            FillQueueDataGrid(filesInFolder);
        }
Ejemplo n.º 10
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);
        }
Ejemplo n.º 11
0
        public override async IAsyncEnumerable <FileSystemStorageItemBase> SearchAsync(string SearchWord, bool SearchInSubFolders = false, bool IncludeHiddenItem = false, bool IncludeSystemItem = false, bool IsRegexExpresstion = false, bool IgnoreCase = true, [EnumeratorCancellation] CancellationToken CancelToken = default)
        {
            foreach (DriveDataBase Drive in CommonAccessCollection.DriveList)
            {
                if (WIN_Native_API.CheckLocationAvailability(Drive.Path))
                {
                    foreach (FileSystemStorageItemBase Item in await Task.Factory.StartNew(() => WIN_Native_API.Search(Drive.Path, SearchWord, SearchInSubFolders, IncludeHiddenItem, IncludeSystemItem, IsRegexExpresstion, IgnoreCase, CancelToken), TaskCreationOptions.LongRunning))
                    {
                        yield return(Item);
                    }
                }
                else
                {
                    if (Drive.DriveFolder != null)
                    {
                        QueryOptions Options = new QueryOptions
                        {
                            FolderDepth   = FolderDepth.Shallow,
                            IndexerOption = IndexerOption.DoNotUseIndexer
                        };
                        Options.SetThumbnailPrefetch(ThumbnailMode.ListView, 150, ThumbnailOptions.UseCurrentScale);
                        Options.SetPropertyPrefetch(PropertyPrefetchOptions.BasicProperties, new string[] { "System.FileName", "System.Size", "System.DateModified", "System.DateCreated" });

                        StorageItemQueryResult Query = Drive.DriveFolder.CreateItemQueryWithOptions(Options);

                        for (uint Index = 0; !CancelToken.IsCancellationRequested; Index += 50)
                        {
                            IReadOnlyList <IStorageItem> ReadOnlyItemList = await Query.GetItemsAsync(Index, 50).AsTask(CancelToken);

                            if (ReadOnlyItemList.Count > 0)
                            {
                                foreach (IStorageItem Item in IsRegexExpresstion
                                                              ? ReadOnlyItemList.AsParallel().Where((Item) => Regex.IsMatch(Item.Name, SearchWord, IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None))
                                                              : ReadOnlyItemList.AsParallel().Where((Item) => Item.Name.Contains(SearchWord, IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)))
                                {
                                    if (CancelToken.IsCancellationRequested)
                                    {
                                        yield break;
                                    }

                                    switch (Item)
                                    {
                                    case StorageFolder SubFolder:
                                    {
                                        yield return(await CreatedByStorageItemAsync(SubFolder));

                                        break;
                                    }

                                    case StorageFile SubFile:
                                    {
                                        yield return(await CreatedByStorageItemAsync(SubFile));

                                        break;
                                    }
                                    }
                                }

                                if (SearchInSubFolders)
                                {
                                    foreach (StorageFolder Item in ReadOnlyItemList.OfType <StorageFolder>())
                                    {
                                        if (CancelToken.IsCancellationRequested)
                                        {
                                            yield break;
                                        }

                                        FileSystemStorageFolder FSubFolder = await CreatedByStorageItemAsync(Item);

                                        await foreach (FileSystemStorageItemBase FSubItem in FSubFolder.SearchAsync(SearchWord, SearchInSubFolders, IncludeHiddenItem, IncludeSystemItem, IsRegexExpresstion, IgnoreCase, CancelToken))
                                        {
                                            if (CancelToken.IsCancellationRequested)
                                            {
                                                yield break;
                                            }

                                            yield return(FSubItem);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 12
0
 public SystemStorageItemQueryResult(StorageItemQueryResult sfqr) : base(sfqr.Folder, sfqr.GetCurrentQueryOptions())
 {
     StorageItemQueryResult = sfqr;
 }
        public async Task <List <FileSystemStorageItemBase> > GetChildItemsAsync(bool IncludeHiddenItems, bool IncludeSystemItem, ItemFilters Filter = ItemFilters.File | ItemFilters.Folder)
        {
            if (WIN_Native_API.CheckLocationAvailability(Path))
            {
                return(WIN_Native_API.GetStorageItems(Path, IncludeHiddenItems, IncludeSystemItem, Filter));
            }
            else
            {
                LogTracer.Log($"Native API could not enum subitems in path: \"{Path}\", fall back to UWP storage API");

                try
                {
                    if (await GetStorageItemAsync() is StorageFolder Folder)
                    {
                        QueryOptions Options = new QueryOptions
                        {
                            FolderDepth   = FolderDepth.Shallow,
                            IndexerOption = IndexerOption.DoNotUseIndexer
                        };
                        Options.SetThumbnailPrefetch(ThumbnailMode.ListView, 150, ThumbnailOptions.UseCurrentScale);
                        Options.SetPropertyPrefetch(PropertyPrefetchOptions.BasicProperties, new string[] { "System.Size", "System.DateModified" });

                        StorageItemQueryResult Query = Folder.CreateItemQueryWithOptions(Options);

                        List <FileSystemStorageItemBase> Result = new List <FileSystemStorageItemBase>();

                        for (uint i = 0; ; i += 25)
                        {
                            IReadOnlyList <IStorageItem> ReadOnlyItemList = await Query.GetItemsAsync(i, 25);

                            if (ReadOnlyItemList.Count > 0)
                            {
                                foreach (IStorageItem Item in ReadOnlyItemList.Where((Item) => (Item.IsOfType(StorageItemTypes.Folder) && Filter.HasFlag(ItemFilters.Folder)) || (Item.IsOfType(StorageItemTypes.File) && Filter.HasFlag(ItemFilters.File))))
                                {
                                    if (Item is StorageFolder SubFolder)
                                    {
                                        Result.Add(new FileSystemStorageFolder(SubFolder, await SubFolder.GetModifiedTimeAsync()));
                                    }
                                    else if (Item is StorageFile SubFile)
                                    {
                                        Result.Add(await CreateFromStorageItemAsync(SubFile));
                                    }
                                }
                            }
                            else
                            {
                                break;
                            }
                        }

                        return(Result);
                    }
                    else
                    {
                        return(new List <FileSystemStorageItemBase>(0));
                    }
                }
                catch
                {
                    LogTracer.Log($"UWP API could not enum subitems in path: \"{Path}\"");
                    return(new List <FileSystemStorageItemBase>(0));
                }
            }
        }
 private async IAsyncEnumerable <IImageSource> AsyncEnumerableItems(uint count, StorageItemQueryResult queryResult, [EnumeratorCancellation] CancellationToken ct = default)
 {
     await foreach (var item in FolderHelper.GetEnumerator(queryResult, count, ct))
     {
         yield return(new StorageItemImageSource(item, _thumbnailManager));
     }
 }
        public async IAsyncEnumerable <FileSystemStorageItemBase> SearchAsync(string SearchWord, bool SearchInSubFolders = false, bool IncludeHiddenItem = false, bool IncludeSystemItem = false, bool IsRegexExpresstion = false, bool IgnoreCase = true, [EnumeratorCancellation] CancellationToken CancelToken = default)
        {
            if (WIN_Native_API.CheckLocationAvailability(Path))
            {
                foreach (FileSystemStorageItemBase Item in await Task.Run(() => WIN_Native_API.Search(Path, SearchWord, SearchInSubFolders, IncludeHiddenItem, IncludeSystemItem, IsRegexExpresstion, IgnoreCase, CancelToken)))
                {
                    yield return(Item);
                }
            }
            else
            {
                if (await GetStorageItemAsync() is StorageFolder Folder)
                {
                    QueryOptions Options = new QueryOptions
                    {
                        FolderDepth   = SearchInSubFolders ? FolderDepth.Deep : FolderDepth.Shallow,
                        IndexerOption = IndexerOption.DoNotUseIndexer
                    };
                    Options.SetThumbnailPrefetch(ThumbnailMode.ListView, 150, ThumbnailOptions.UseCurrentScale);
                    Options.SetPropertyPrefetch(PropertyPrefetchOptions.BasicProperties, new string[] { "System.FileName", "System.Size", "System.DateModified", "System.DateCreated" });

                    if (!IsRegexExpresstion)
                    {
                        Options.ApplicationSearchFilter = $"System.FileName:~=\"{SearchWord}\"";
                    }

                    StorageItemQueryResult Query = Folder.CreateItemQueryWithOptions(Options);

                    for (uint Index = 0; !CancelToken.IsCancellationRequested; Index += 25)
                    {
                        IReadOnlyList <IStorageItem> ReadOnlyItemList = await Query.GetItemsAsync(Index, 25);

                        if (ReadOnlyItemList.Count > 0)
                        {
                            IEnumerable <IStorageItem> Result = IsRegexExpresstion
                                                                ? ReadOnlyItemList.Where((Item) => Regex.IsMatch(Item.Name, SearchWord, IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None))
                                                                : ReadOnlyItemList.Where((Item) => Item.Name.Contains(SearchWord, IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal));

                            foreach (IStorageItem Item in Result)
                            {
                                if (CancelToken.IsCancellationRequested)
                                {
                                    yield break;
                                }

                                switch (Item)
                                {
                                case StorageFolder SubFolder:
                                {
                                    yield return(new FileSystemStorageFolder(SubFolder, await SubFolder.GetModifiedTimeAsync()));

                                    break;
                                }

                                case StorageFile SubFile:
                                {
                                    yield return(await CreateFromStorageItemAsync(SubFile));

                                    break;
                                }
                                }
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
        }
        public async Task <(uint, uint)> GetFolderAndFileNumAsync(CancellationToken CancelToken = default)
        {
            if (WIN_Native_API.CheckLocationAvailability(Path))
            {
                return(await Task.Run(() =>
                {
                    return WIN_Native_API.CalculateFolderAndFileCount(Path, CancelToken);
                }));
            }
            else
            {
                try
                {
                    LogTracer.Log($"Native API could not found the path: \"{Path}\", fall back to UWP storage API");

                    if (await GetStorageItemAsync() is StorageFolder Folder)
                    {
                        QueryOptions Options = new QueryOptions
                        {
                            FolderDepth   = FolderDepth.Deep,
                            IndexerOption = IndexerOption.DoNotUseIndexer
                        };
                        Options.SetPropertyPrefetch(PropertyPrefetchOptions.BasicProperties, new string[] { "System.Size" });

                        StorageItemQueryResult Query = Folder.CreateItemQueryWithOptions(Options);

                        uint FolderCount = 0, FileCount = 0;

                        for (uint Index = 0; !CancelToken.IsCancellationRequested; Index += 25)
                        {
                            IReadOnlyList <IStorageItem> ReadOnlyItemList = await Query.GetItemsAsync(Index, 25);

                            if (ReadOnlyItemList.Count > 0)
                            {
                                foreach (IStorageItem Item in ReadOnlyItemList)
                                {
                                    if (Item.IsOfType(StorageItemTypes.Folder))
                                    {
                                        FolderCount++;
                                    }
                                    else
                                    {
                                        FileCount++;
                                    }

                                    if (CancelToken.IsCancellationRequested)
                                    {
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                break;
                            }
                        }

                        return(FolderCount, FileCount);
                    }
                    else
                    {
                        return(0, 0);
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"{nameof(GetFolderAndFileNumAsync)} failed for uwp API");
                    return(0, 0);
                }
            }
        }
Ejemplo n.º 17
0
        private async Task <IEnumerable <FileSystemStorageItemBase> > GetMoreItemsFunction(uint Index, uint Num, StorageItemQueryResult Query)
        {
            List <FileSystemStorageItemBase> ItemList = new List <FileSystemStorageItemBase>();

            foreach (var Item in await Query.GetItemsAsync(Index, Num))
            {
                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);

                ItemList.Add(new FileSystemStorageItemBase(Item as StorageFile, Size, Thumbnail, ModifiedTime));
            }
            return(ItemList);
        }
Ejemplo n.º 18
0
        /// Actions



        async Task InitialScan()
        {
            var stopwatch = Stopwatch.StartNew();

            ReportLine("Started initial scan\n");

            StorageItemQueryResult query = CreateQuery();

            try
            {
                using (await _lock.LockAsync())
                {
                    int  itemIndex  = 0;
                    uint chunkIndex = 0;
                    uint chunkSize  = 50;
                    var  chunkItems = new List <MonitoredFolderItem>((int)chunkSize);
                    int  addedCount = 0;

                    do
                    {
                        if (_cancellationToken.IsCancellationRequested)
                        {
                            break;
                        }

                        // Get items
                        var items = await query.GetItemsAsync(chunkIndex, chunkSize);

                        if (!items.Any())
                        {
                            break;
                        }

                        Report(".");

                        // Gather added items
                        chunkItems.Clear();
                        foreach (var item in items)
                        {
                            if (_cancellationToken.IsCancellationRequested)
                            {
                                break;
                            }

                            var itemName = item.Name;

                            var newItem = new MonitoredFolderItem(item);
                            _cachedItems.Insert(itemIndex, newItem);

                            chunkItems.Add(newItem);
                            itemIndex++;
                        }

                        if (_cancellationToken.IsCancellationRequested)
                        {
                            break;
                        }

                        if (chunkItems.Any())
                        {
                            addedCount += chunkItems.Count;

                            // Raise event
                            Changed?.Invoke(this, new MonitoredFolderChangedArgs(chunkItems));
                        }

                        // Move Next
                        chunkIndex += (uint)items.Count();
                    }while (true);

                    stopwatch.Stop();

                    ReportLine($"+{addedCount}");
                    ReportLine($"Finished initial scan.  Processed {chunkIndex} items in {stopwatch.ElapsedMilliseconds} ms.");

                    ReportLine("Releasing Lock");
                }
            }
            catch (Exception ex)
            {
                ReportLine($"Exception\n{ex}");
            }
        }
Ejemplo n.º 19
0
        public async IAsyncEnumerable <FileSystemStorageItemBase> SearchAsync(string SearchWord, bool SearchInSubFolders = false, bool IncludeHiddenItem = false, bool IsRegexExpresstion = false, bool IgnoreCase = true, [EnumeratorCancellation] CancellationToken CancelToken = default)
        {
            if (WIN_Native_API.CheckLocationAvailability(Path))
            {
                List <FileSystemStorageItemBase> SearchResult = await Task.Run(() =>
                {
                    return(WIN_Native_API.Search(Path, SearchWord, SearchInSubFolders, IncludeHiddenItem, IsRegexExpresstion, IgnoreCase, CancelToken));
                });

                foreach (FileSystemStorageItemBase Item in SearchResult)
                {
                    yield return(Item);

                    if (CancelToken.IsCancellationRequested)
                    {
                        yield break;
                    }
                }
            }
            else
            {
                if (await GetStorageItemAsync().ConfigureAwait(true) is StorageFolder Folder)
                {
                    QueryOptions Options = new QueryOptions
                    {
                        FolderDepth   = SearchInSubFolders ? FolderDepth.Deep : FolderDepth.Shallow,
                        IndexerOption = IndexerOption.UseIndexerWhenAvailable
                    };
                    Options.SetThumbnailPrefetch(Windows.Storage.FileProperties.ThumbnailMode.ListView, 150, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale);
                    Options.SetPropertyPrefetch(Windows.Storage.FileProperties.PropertyPrefetchOptions.BasicProperties, new string[] { "System.Size", "System.DateModified" });

                    if (!IsRegexExpresstion)
                    {
                        Options.ApplicationSearchFilter = $"System.FileName:*{SearchWord}*";
                    }

                    StorageItemQueryResult Query = Folder.CreateItemQueryWithOptions(Options);

                    uint FileCount = await Query.GetItemCountAsync();

                    for (uint Index = 0; Index < FileCount && !CancelToken.IsCancellationRequested; Index += 50)
                    {
                        IEnumerable <IStorageItem> Result = IsRegexExpresstion
                                                            ? (await Query.GetItemsAsync(Index, 50)).Where((Item) => Regex.IsMatch(Item.Name, SearchWord, IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None))
                                                            : (await Query.GetItemsAsync(Index, 50)).Where((Item) => Item.Name.Contains(SearchWord, IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal));

                        foreach (IStorageItem Item in Result)
                        {
                            switch (Item)
                            {
                            case StorageFolder SubFolder:
                            {
                                yield return(new FileSystemStorageFolder(SubFolder, await SubFolder.GetThumbnailBitmapAsync().ConfigureAwait(true), await SubFolder.GetModifiedTimeAsync().ConfigureAwait(true)));

                                break;
                            }

                            case StorageFile SubFile:
                            {
                                yield return(new FileSystemStorageFile(SubFile, await SubFile.GetThumbnailBitmapAsync().ConfigureAwait(true), await SubFile.GetSizeRawDataAsync().ConfigureAwait(true), await SubFile.GetModifiedTimeAsync().ConfigureAwait(true)));

                                break;
                            }
                            }

                            if (CancelToken.IsCancellationRequested)
                            {
                                yield break;
                            }
                        }
                    }
                }
            }
        }