protected override async Task <List <string> > GetFileNamesAsync()
        {
            // Query to retreive colorings ordered by date modified.
            QueryOptions queryOptions = new QueryOptions(CommonFolderQuery.DefaultQuery);

            queryOptions.SortOrder.Clear();

            SortEntry se = new SortEntry
            {
                PropertyName   = "System.DateModified",
                AscendingOrder = false
            };

            queryOptions.SortOrder.Add(se);

            var assetsDir = await Tools.GetAssetsFolderAsync();

            var libraryImagesDir = await Tools.GetSubDirectoryAsync(assetsDir, "LibraryImages");

            StorageFolderQueryResult queryResult = libraryImagesDir.CreateFolderQueryWithOptions(queryOptions);

            var libraryImages = await queryResult.GetFoldersAsync();

            return(libraryImages.Select(image => image.Name).ToList());
        }
        /// <summary>
        /// helper for all list by functions
        /// </summary>
        private async Task GroupByHelperAsync(QueryOptions queryOptions)
        {
            GroupedFiles.Clear();

            StorageFolder picturesFolder = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);

            StorageFolderQueryResult queryResult = picturesFolder.CreateFolderQueryWithOptions(queryOptions);

            IReadOnlyList <StorageFolder> folderList = await queryResult.GetFoldersAsync();

            foreach (StorageFolder folder in folderList)
            {
                IReadOnlyList <StorageFile> fileList = await folder.GetFilesAsync();

                var newList = new List <string>();

                newList.Add("Group: " + folder.Name + " (" + fileList.Count + ")");

                GroupedFiles.Add(newList);
                foreach (StorageFile file in fileList)
                {
                    newList.Add(file.Name);
                }
            }
        }
Ejemplo n.º 3
0
        // 分组文件夹
        private async void btnFolderGroup_Click(object sender, RoutedEventArgs e)
        {
            lblMsg.Text = "";

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

            // 文件夹按月分组查询参数,其他多种分组方式请参见 CommonFolderQuery 枚举
            CommonFolderQuery folderQuery = CommonFolderQuery.GroupByMonth;

            // 判断一下 picturesFolder 是否支持指定的查询参数
            if (picturesFolder.IsCommonFolderQuerySupported(folderQuery))
            {
                // 创建查询
                StorageFolderQueryResult queryResult = picturesFolder.CreateFolderQuery(folderQuery);

                // 执行查询
                IReadOnlyList <StorageFolder> folderList = await queryResult.GetFoldersAsync();

                foreach (StorageFolder storageFolder in folderList) // 这里的 storageFolder 就是按月份分组后的月份文件夹(当然,物理上并没有月份文件夹)
                {
                    IReadOnlyList <StorageFile> fileList = await storageFolder.GetFilesAsync();

                    lblMsg.Text += storageFolder.Name + " (" + fileList.Count + ")";
                    lblMsg.Text += Environment.NewLine;
                    foreach (StorageFile file in fileList) // 月份文件夹内的文件
                    {
                        lblMsg.Text += "    " + file.Name;
                        lblMsg.Text += Environment.NewLine;
                    }
                }
            }
        }
Ejemplo n.º 4
0
        public async Task <String> carpeta()
        {
            StorageFolder picturesFolder = KnownFolders.PicturesLibrary;

            StorageFolderQueryResult queryResult =
                picturesFolder.CreateFolderQuery(CommonFolderQuery.GroupByMonth);

            IReadOnlyList <StorageFolder> folderList =
                await queryResult.GetFoldersAsync();

            StringBuilder outputText = new StringBuilder();

            foreach (StorageFolder folder in folderList)
            {
                IReadOnlyList <StorageFile> fileList = await folder.GetFilesAsync();

                // Print the month and number of files in this group.
                outputText.AppendLine(folder.Name + " (" + fileList.Count + ")");

                foreach (StorageFile file in fileList)
                {
                    // Print the name of the file.
                    outputText.AppendLine("   " + file.Name);
                }
            }

            return(Convert.ToString(outputText));
        }
        public async void playMedia(string mediaType, string videoName)
        {
            mediaPlayerElement.Source = null;

            StorageFolder chosenFolder = null;

            if (mediaType == "video")
            {
                chosenFolder = KnownFolders.VideosLibrary;
            }
            else if (mediaType == "music")
            {
                chosenFolder = KnownFolders.MusicLibrary;
            }


            StorageFolderQueryResult queryResult = chosenFolder.CreateFolderQuery(Windows.Storage.Search.CommonFolderQuery.GroupByMonth);

            IReadOnlyList <StorageFolder> folderList = await queryResult.GetFoldersAsync();

            foreach (StorageFolder folder in folderList)
            {
                IReadOnlyList <StorageFile> fileList = await folder.GetFilesAsync();

                foreach (StorageFile file in fileList)
                {
                    if (file.Name.StartsWith(videoName))
                    {
                        this.mediaPlayerElement.MediaPlayer.Source = MediaSource.CreateFromStorageFile(file);
                        this.mediaPlayerElement.MediaPlayer.Play();
                    }
                }
            }
        }
Ejemplo n.º 6
0
        private async void Button_Click3(object sender, RoutedEventArgs e)
        {
            StorageFolder picturesFolder = KnownFolders.PicturesLibrary;

            StorageFolderQueryResult queryResult = picturesFolder.CreateFolderQuery(CommonFolderQuery.GroupByMonth);

            IReadOnlyList <StorageFolder> folderList = await queryResult.GetFoldersAsync();

            StringBuilder outputText = new StringBuilder();

            foreach (StorageFolder folder in folderList)
            {
                IReadOnlyList <StorageFile> fileList = await folder.GetFilesAsync();

                // Print the month and number of files in this group.
                outputText.AppendLine(folder.Name + " (" + fileList.Count + ")");

                foreach (StorageFile file in fileList)
                {
                    // Print the name of the file.
                    outputText.AppendLine("   " + file.Name);
                }
            }
            MyText.Text = outputText.ToString() + "\nPath:==" + picturesFolder.Path;
        }
Ejemplo n.º 7
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.º 8
0
        public async static Task <IList <StorageFolderWithPath> > GetFoldersWithPathAsync(this StorageFolderWithPath parentFolder, string nameFilter, uint maxNumberOfItems = uint.MaxValue)
        {
            var queryOptions = new QueryOptions();

            queryOptions.ApplicationSearchFilter = $"System.FileName:{nameFilter}*";
            StorageFolderQueryResult queryResult = parentFolder.Folder.CreateFolderQueryWithOptions(queryOptions);

            return((await queryResult.GetFoldersAsync(0, maxNumberOfItems)).Select(x => new StorageFolderWithPath(x, Path.Combine(parentFolder.Path, x.Name))).ToList());
        }
Ejemplo n.º 9
0
        public async Task updatePhraseLists(string mediaType)
        {
            try
            {
                // Update the video phrase list, so that Cortana voice commands can use videos found in system.
                //Adapted from Miscrosoft docs: https://docs.microsoft.com/en-us/cortana/voicecommands/dynamically-modify-voice-command-definition-vcd-phrase-lists

                VoiceCommandDefinition commandDefinitions;
                StorageFolder          videoFolder = null;

                switch (mediaType)
                {
                case "video":
                    videoFolder = KnownFolders.VideosLibrary;
                    break;

                case "music":
                    videoFolder = KnownFolders.MusicLibrary;
                    break;
                }

                if (VoiceCommandDefinitionManager.InstalledCommandDefinitions.TryGetValue("ProjectCommandSet_en-us", out commandDefinitions))
                {
                    StorageFolderQueryResult queryResult = videoFolder.CreateFolderQuery(Windows.Storage.Search.CommonFolderQuery.GroupByMonth);

                    IReadOnlyList <StorageFolder> folderList = await queryResult.GetFoldersAsync();

                    List <string> namesList = new List <string>();

                    foreach (StorageFolder folder in folderList)
                    {
                        IReadOnlyList <StorageFile> fileList = await folder.GetFilesAsync();

                        foreach (StorageFile file in fileList)
                        {
                            namesList.Add(Path.GetFileNameWithoutExtension(file.Name));
                        }
                    }


                    //add video names to phraselist
                    await commandDefinitions.SetPhraseListAsync(mediaType, namesList);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Error updating Phrase list for VCDs: " + ex.ToString());
            }
        }
Ejemplo n.º 10
0
        private async void ApplyFilter(object sender, RoutedEventArgs e)
        {
            if (canAddFilter == false)
            {
                return;
            }

            StorageFolder assetsFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets");

            StorageFolderQueryResult      results = assetsFolder.CreateFolderQuery();
            IReadOnlyList <StorageFolder> folders = await results.GetFoldersAsync();

            StorageFolder filterFolder = folders.Where(fol => fol.DisplayName == "Filters").First();

            filters = await filterFolder.GetFilesAsync();

            /*Debug.WriteLine("Displaying Folder");
             * Debug.WriteLine(filterFolder.DisplayName);
             *
             * Debug.WriteLine("Displaying filter names");
             *
             * foreach (StorageFile fil in filters)
             * {
             *  Debug.WriteLine(fil.DisplayName);
             * }*/


            Image filter = new Image();

            filter.VerticalAlignment   = VerticalAlignment.Center;
            filter.HorizontalAlignment = HorizontalAlignment.Center;

            BitmapImage bm = new BitmapImage(new Uri(filters[0].Path));

            filter.Source = bm;

            Canvas.SetZIndex(filter, 1);
            this.renderTarget.Children.Add(filter);

            currentFilter = filter;
            filterCount++;
            canAddFilter = (filterCount == 5) ? !canAddFilter : canAddFilter;

            if (canAddFilter == false)
            {
                Debug.WriteLine("Cannot apply filter");
            }
        }
        private async Task LoadFoldersAsync(CancellationToken cancellationToken)
        {
            uint si = 0;
            IReadOnlyList <StorageFolder> folders;

            do
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }

                folders = await folderQuery.GetFoldersAsync(si, FILE_RETRIEVE_STEPSIZE);
                await AddFoldersAsync(folders, cancellationToken);

                si += FILE_RETRIEVE_STEPSIZE;
            } while (folders.Count != 0);
        }
Ejemplo n.º 12
0
        private async static Task <IReadOnlyList <StorageFolder> > GetWslDriveAsync()
        {
            try
            {
                StorageFolder WslBaseFolder = await StorageFolder.GetFolderFromPathAsync(@"\\wsl$");

                StorageFolderQueryResult Query = WslBaseFolder.CreateFolderQueryWithOptions(new QueryOptions
                {
                    FolderDepth   = FolderDepth.Shallow,
                    IndexerOption = IndexerOption.DoNotUseIndexer
                });

                return(await Query.GetFoldersAsync());
            }
            catch
            {
                return(new List <StorageFolder>(0));
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// helper for all list by functions
        /// </summary>
        async Task GroupByHelperAsync(QueryOptions queryOptions)
        {
            OutputPanel.Children.Clear();

            StorageFolder            picturesFolder = KnownFolders.PicturesLibrary;
            StorageFolderQueryResult queryResult    = picturesFolder.CreateFolderQueryWithOptions(queryOptions);

            IReadOnlyList <StorageFolder> folderList = await queryResult.GetFoldersAsync();

            foreach (StorageFolder folder in folderList)
            {
                IReadOnlyList <StorageFile> fileList = await folder.GetFilesAsync();

                OutputPanel.Children.Add(CreateHeaderTextBlock(folder.Name + " (" + fileList.Count + ")"));
                foreach (StorageFile file in fileList)
                {
                    OutputPanel.Children.Add(CreateLineItemTextBlock(file.Name));
                }
            }
        }
Ejemplo n.º 14
0
        //按月分组,每个虚拟文件夹都表示一组具有相同月份的文件。
        async public void selectfilesbymonth()
        {
            StorageFolder            sf          = KnownFolders.PicturesLibrary;
            StorageFolderQueryResult queryResult = sf.CreateFolderQuery(CommonFolderQuery.GroupByMonth);

            IReadOnlyList <StorageFolder> folderList = await queryResult.GetFoldersAsync();

            StringBuilder stringBuilder = new StringBuilder();

            foreach (StorageFolder folder in folderList)
            {
                IReadOnlyList <StorageFile> storageFiles = await folder.GetFilesAsync();

                stringBuilder.AppendLine(folder.Name + "(" + storageFiles.Count + ")");
                foreach (StorageFile file in storageFiles)
                {
                    stringBuilder.AppendLine("  " + file.Name);
                }
            }
            outputtextblock3.Text = stringBuilder.ToString();
        }
Ejemplo n.º 15
0
            private async Task LoadAlbums(StorageFolderQueryResult albumQueryResult, int artistId)
            {
                IReadOnlyList <StorageFolder> albumFolders = null;

                try
                {
                    albumFolders = await albumQueryResult.GetFoldersAsync();
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.ToString());
                }
                if (albumFolders != null)
                {
                    foreach (var item in albumFolders)
                    {
                        AlbumItem albumItem = await GetInformationsFromMusicFile.GetAlbumItemFromFolder(item, albumQueryResult, artistId);

                        await albumItem.GetCover();

                        // Album is in database, update with cover.
                        await _albumDataRepository.Update(albumItem);

                        await DispatchHelper.InvokeAsync(() =>
                        {
                            Albums.Add(albumItem);
                            if (Locator.MusicLibraryVM.RandomAlbums.Count < 12)
                            {
                                Locator.MusicLibraryVM.RandomAlbums.Add(albumItem);
                            }
                        });

                        Locator.MusicLibraryVM.AlbumCover.Add(albumItem.Picture);
                    }
                }
            }
        public async void polulateListBox(string mediaType)
        {
            StorageFolder chosenFolder = null;

            if (mediaType == "videos")
            {
                chosenFolder = KnownFolders.VideosLibrary;
            }
            else if (mediaType == "music")
            {
                chosenFolder = KnownFolders.MusicLibrary;
            }

            StorageFolderQueryResult      queryResult    = chosenFolder.CreateFolderQuery(Windows.Storage.Search.CommonFolderQuery.GroupByAlbumArtist);
            IReadOnlyList <StorageFolder> tempFolderList = await queryResult.GetFoldersAsync();

            //clear fileList before populating
            fileList.Clear();

            mySpiltView.IsPaneOpen = true;


            foreach (StorageFolder folder in tempFolderList)
            {
                //create tempfileList for reading
                IReadOnlyList <StorageFile> tempFileList = await folder.GetFilesAsync();

                foreach (StorageFile file in tempFileList)
                {
                    //add to mediaListBox for displaying to user
                    mediaListBox.Items.Add(Path.GetFileNameWithoutExtension(file.Name));
                    //add to fileList for playing after selection
                    fileList.Add(file);
                }
            }
        }
Ejemplo n.º 17
0
        private async void FileContentsChanged(IStorageQueryResultBase sender, object args)
        {
            if (_filesRefreshing)
            {
                Debug.WriteLine("Filesystem change event fired but refresh is already running");
                return;
            }
            else
            {
                Debug.WriteLine("Filesystem change event fired. Refreshing...");
            }

            _filesRefreshing = true;

            //query options have to be reapplied otherwise old results are returned
            _fileQueryResult.ApplyNewQueryOptions(_options);
            _folderQueryResult.ApplyNewQueryOptions(_options);

            var fileCount = await _fileQueryResult.GetItemCountAsync();

            var folderCount = await _folderQueryResult.GetItemCountAsync();

            var files = await _fileQueryResult.GetFilesAsync();

            var folders = await _folderQueryResult.GetFoldersAsync();

            var cancellationTokenSourceCopy = _cancellationTokenSource;

            // modifying a file also results in a new unique FolderRelativeId so no need to check for DateModified explicitly

            var addedFiles             = files.Select(f => f.FolderRelativeId).Except(_filesAndFolders.Select(f => f.FolderRelativeId));
            var addedFolders           = folders.Select(f => f.FolderRelativeId).Except(_filesAndFolders.Select(f => f.FolderRelativeId));
            var removedFilesAndFolders = _filesAndFolders
                                         .Select(f => f.FolderRelativeId)
                                         .Except(files.Select(f => f.FolderRelativeId))
                                         .Except(folders.Select(f => f.FolderRelativeId))
                                         .ToArray();

            foreach (var file in addedFiles)
            {
                var toAdd = files.First(f => f.FolderRelativeId == file);
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                              async() =>
                {
                    await AddFile(toAdd, _pageName, cancellationTokenSourceCopy.Token);
                });
            }
            foreach (var folder in addedFolders)
            {
                var toAdd = folders.First(f => f.FolderRelativeId == folder);
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                              async() =>
                {
                    await AddFolder(toAdd, _pageName, cancellationTokenSourceCopy.Token);
                });
            }
            foreach (var item in removedFilesAndFolders)
            {
                var toRemove = _filesAndFolders.First(f => f.FolderRelativeId == item);
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                              () =>
                {
                    RemoveFileOrFolder(toRemove);
                });
            }

            _filesRefreshing = false;
            Debug.WriteLine("Filesystem refresh complete");
        }
Ejemplo n.º 18
0
        public async void MemoryFriendlyGetItemsAsync(string path, Page passedPage)
        {
            TextState.isVisible = Visibility.Collapsed;
            tokenSource         = new CancellationTokenSource();
            CancellationToken token = App.ViewModel.tokenSource.Token;

            pageName       = passedPage.Name;
            Universal.path = path;
            // Personalize retrieved items for view they are displayed in
            switch (pageName)
            {
            case "GenericItemView":
                isPhotoAlbumMode = false;
                break;

            case "PhotoAlbumViewer":
                isPhotoAlbumMode = true;
                break;

            case "ClassicModePage":
                isPhotoAlbumMode = false;
                break;
            }

            if (pageName != "ClassicModePage")
            {
                FilesAndFolders.Clear();
            }

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            Universal.path = path;      // Set visible path to reflect new navigation
            try
            {
                PVIS.isVisible      = Visibility.Visible;
                TextState.isVisible = Visibility.Collapsed;
                switch (Universal.path)
                {
                case "Desktop":
                    Universal.path = MainPage.DesktopPath;
                    break;

                case "Downloads":
                    Universal.path = MainPage.DownloadsPath;
                    break;

                case "Documents":
                    Universal.path = MainPage.DocumentsPath;
                    break;

                case "Pictures":
                    Universal.path = MainPage.PicturesPath;
                    break;

                case "Music":
                    Universal.path = MainPage.MusicPath;
                    break;

                case "Videos":
                    Universal.path = MainPage.VideosPath;
                    break;

                case "OneDrive":
                    Universal.path = MainPage.OneDrivePath;
                    break;
                }

                folder = await StorageFolder.GetFolderFromPathAsync(Universal.path);

                History.AddToHistory(Universal.path);

                if (History.HistoryList.Count == 1)
                {
                    BS.isEnabled = false;
                }
                else if (History.HistoryList.Count > 1)
                {
                    BS.isEnabled = true;
                }

                QueryOptions options = new QueryOptions()
                {
                    FolderDepth   = FolderDepth.Shallow,
                    IndexerOption = IndexerOption.UseIndexerWhenAvailable
                };
                string sort = "By_Name";
                if (sort == "By_Name")
                {
                    SortEntry entry = new SortEntry()
                    {
                        AscendingOrder = true,
                        PropertyName   = "System.FileName"
                    };
                    options.SortOrder.Add(entry);
                }

                uint       index = 0;
                const uint step  = 250;
                if (!folder.AreQueryOptionsSupported(options))
                {
                    options.SortOrder.Clear();
                }

                folderQueryResult = folder.CreateFolderQueryWithOptions(options);
                IReadOnlyList <StorageFolder> folders = await folderQueryResult.GetFoldersAsync(index, step);

                int foldersCountSnapshot = folders.Count;
                while (folders.Count != 0)
                {
                    foreach (StorageFolder folder in folders)
                    {
                        if (token.IsCancellationRequested)
                        {
                            return;
                        }

                        gotFolName     = folder.Name.ToString();
                        gotFolDate     = folder.DateCreated.ToString();
                        gotFolPath     = folder.Path.ToString();
                        gotFolType     = "Folder";
                        gotFolImg      = Visibility.Visible;
                        gotFileImgVis  = Visibility.Collapsed;
                        gotEmptyImgVis = Visibility.Collapsed;


                        if (pageName == "ClassicModePage")
                        {
                            ClassicFolderList.Add(new Classic_ListedFolderItem()
                            {
                                FileName = gotFolName, FileDate = gotFolDate, FileExtension = gotFolType, FilePath = gotFolPath
                            });
                        }
                        else
                        {
                            FilesAndFolders.Add(new ListedItem()
                            {
                                EmptyImgVis = gotEmptyImgVis, ItemIndex = FilesAndFolders.Count, FileImg = null, FileIconVis = gotFileImgVis, FolderImg = gotFolImg, FileName = gotFolName, FileDate = gotFolDate, FileExtension = gotFolType, FilePath = gotFolPath
                            });
                        }
                    }
                    index  += step;
                    folders = await folderQueryResult.GetFoldersAsync(index, step);
                }

                index           = 0;
                fileQueryResult = folder.CreateFileQueryWithOptions(options);
                IReadOnlyList <StorageFile> files = await fileQueryResult.GetFilesAsync(index, step);

                int filesCountSnapshot = files.Count;
                while (files.Count != 0)
                {
                    foreach (StorageFile file in files)
                    {
                        if (token.IsCancellationRequested)
                        {
                            return;
                        }

                        gotName = file.DisplayName.ToString();
                        gotDate = file.DateCreated.ToString(); // In the future, parse date to human readable format
                        if (file.FileType.ToString() == ".exe")
                        {
                            gotType = "Executable";
                        }
                        else
                        {
                            gotType = file.DisplayType;
                        }
                        gotPath             = file.Path.ToString();
                        gotFolImg           = Visibility.Collapsed;
                        gotDotFileExtension = file.FileType;
                        if (isPhotoAlbumMode == false)
                        {
                            const uint             requestedSize    = 20;
                            const ThumbnailMode    thumbnailMode    = ThumbnailMode.ListView;
                            const ThumbnailOptions thumbnailOptions = ThumbnailOptions.UseCurrentScale;
                            try
                            {
                                gotFileImg = await file.GetThumbnailAsync(thumbnailMode, requestedSize, thumbnailOptions);

                                BitmapImage icon = new BitmapImage();
                                if (gotFileImg != null)
                                {
                                    gotEmptyImgVis = Visibility.Collapsed;
                                    icon.SetSource(gotFileImg.CloneStream());
                                }
                                else
                                {
                                    gotEmptyImgVis = Visibility.Visible;
                                }
                                gotFileImgVis = Visibility.Visible;

                                if (pageName == "ClassicModePage")
                                {
                                    ClassicFileList.Add(new ListedItem()
                                    {
                                        FileImg = icon, FileIconVis = gotFileImgVis, FolderImg = gotFolImg, FileName = gotName, FileDate = gotDate, FileExtension = gotType, FilePath = gotPath
                                    });
                                }
                                else
                                {
                                    FilesAndFolders.Add(new ListedItem()
                                    {
                                        DotFileExtension = gotDotFileExtension, EmptyImgVis = gotEmptyImgVis, FileImg = icon, FileIconVis = gotFileImgVis, FolderImg = gotFolImg, FileName = gotName, FileDate = gotDate, FileExtension = gotType, FilePath = gotPath
                                    });
                                }
                            }
                            catch
                            {
                                // Silent catch here to avoid crash
                                // TODO maybe some logging could be added in the future...
                            }
                        }
                        else
                        {
                            const uint             requestedSize    = 275;
                            const ThumbnailMode    thumbnailMode    = ThumbnailMode.PicturesView;
                            const ThumbnailOptions thumbnailOptions = ThumbnailOptions.ResizeThumbnail;
                            try
                            {
                                gotFileImg = await file.GetThumbnailAsync(thumbnailMode, requestedSize, thumbnailOptions);

                                BitmapImage icon = new BitmapImage();
                                if (gotFileImg != null)
                                {
                                    gotEmptyImgVis = Visibility.Collapsed;
                                    icon.SetSource(gotFileImg.CloneStream());
                                }
                                else
                                {
                                    gotEmptyImgVis = Visibility.Visible;
                                }
                                gotFileImgVis = Visibility.Visible;

                                if (pageName == "ClassicModePage")
                                {
                                    ClassicFileList.Add(new ListedItem()
                                    {
                                        FileImg = icon, FileIconVis = gotFileImgVis, FolderImg = gotFolImg, FileName = gotName, FileDate = gotDate, FileExtension = gotType, FilePath = gotPath
                                    });
                                }
                                else
                                {
                                    FilesAndFolders.Add(new ListedItem()
                                    {
                                        DotFileExtension = gotDotFileExtension, EmptyImgVis = gotEmptyImgVis, FileImg = icon, FileIconVis = gotFileImgVis, FolderImg = gotFolImg, FileName = gotName, FileDate = gotDate, FileExtension = gotType, FilePath = gotPath
                                    });
                                }
                            }
                            catch
                            {
                                // Silent catch here to avoid crash
                                // TODO maybe some logging could be added in the future...
                            }
                        }
                    }
                    index += step;
                    files  = await fileQueryResult.GetFilesAsync(index, step);
                }
                if (foldersCountSnapshot + filesCountSnapshot == 0)
                {
                    TextState.isVisible = Visibility.Visible;
                }
                if (pageName != "ClassicModePage")
                {
                    PVIS.isVisible = Visibility.Collapsed;
                }
                PVIS.isVisible = Visibility.Collapsed;
                stopwatch.Stop();
                Debug.WriteLine("Loading of: " + path + " completed in " + stopwatch.ElapsedMilliseconds + " Milliseconds.");
            }
            catch (UnauthorizedAccessException e)
            {
                if (path.Contains(@"C:\"))
                {
                    DisplayConsentDialog();
                }
                else
                {
                    MessageDialog unsupportedDevice = new MessageDialog("This device may be unsupported. Please file an issue report in Settings - About containing what device we couldn't access. Technical information: " + e, "Unsupported Device");
                    await unsupportedDevice.ShowAsync();
                }
                stopwatch.Stop();
                Debug.WriteLine("Loading of: " + Universal.path + " failed in " + stopwatch.ElapsedMilliseconds + " Milliseconds.");
            }
            catch (COMException e)
            {
                stopwatch.Stop();
                Debug.WriteLine("Loading of: " + Universal.path + " failed in " + stopwatch.ElapsedMilliseconds + " Milliseconds.");
                Frame         rootFrame = Window.Current.Content as Frame;
                MessageDialog driveGone = new MessageDialog(e.Message, "Drive Unplugged");
                await driveGone.ShowAsync();

                rootFrame.Navigate(typeof(MainPage), new SuppressNavigationTransitionInfo());
            }

            tokenSource = null;
        }
Ejemplo n.º 19
0
        public async void AddItemsToCollectionAsync(string path, Page currentPage)
        {
            CancelLoadAndClearFiles();

            _cancellationTokenSource = new CancellationTokenSource();
            var tokenSourceCopy = _cancellationTokenSource;

            TextState.isVisible = Visibility.Collapsed;

            _pageName      = currentPage.Name;
            Universal.path = path;

            if (!_pageName.Contains("Classic"))
            {
                _filesAndFolders.Clear();
            }

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            PVIS.isVisible = Visibility.Visible;

            switch (Universal.path)
            {
            case "Desktop":
                Universal.path = MainPage.DesktopPath;
                break;

            case "Downloads":
                Universal.path = MainPage.DownloadsPath;
                break;

            case "Documents":
                Universal.path = MainPage.DocumentsPath;
                break;

            case "Pictures":
                Universal.path = MainPage.PicturesPath;
                break;

            case "Music":
                Universal.path = MainPage.MusicPath;
                break;

            case "Videos":
                Universal.path = MainPage.VideosPath;
                break;

            case "OneDrive":
                Universal.path = MainPage.OneDrivePath;
                break;
            }

            try
            {
                _rootFolder = await StorageFolder.GetFolderFromPathAsync(Universal.path);

                History.AddToHistory(Universal.path);
                if (History.HistoryList.Count == 1)     // If this is the only item present in History, we don't want back button to be enabled
                {
                    BS.isEnabled = false;
                }
                else if (History.HistoryList.Count > 1)     // Otherwise, if this is not the first item, we'll enable back click
                {
                    BS.isEnabled = true;
                }

                switch (await _rootFolder.GetIndexedStateAsync())
                {
                case (IndexedState.FullyIndexed):
                    _options             = new QueryOptions();
                    _options.FolderDepth = FolderDepth.Shallow;
                    if (_pageName.Contains("Generic"))
                    {
                        _options.SetThumbnailPrefetch(ThumbnailMode.ListView, 20, ThumbnailOptions.UseCurrentScale);
                        _options.SetPropertyPrefetch(PropertyPrefetchOptions.BasicProperties, new string[] { "System.DateModified", "System.ContentType", "System.Size", "System.FileExtension" });
                    }
                    else if (_pageName.Contains("Photo"))
                    {
                        _options.SetThumbnailPrefetch(ThumbnailMode.PicturesView, 275, ThumbnailOptions.ResizeThumbnail);
                        _options.SetPropertyPrefetch(PropertyPrefetchOptions.BasicProperties, new string[] { "System.FileExtension" });
                    }
                    _options.IndexerOption = IndexerOption.OnlyUseIndexerAndOptimizeForIndexedProperties;
                    break;

                default:
                    _options             = new QueryOptions();
                    _options.FolderDepth = FolderDepth.Shallow;
                    if (_pageName.Contains("Generic"))
                    {
                        _options.SetThumbnailPrefetch(ThumbnailMode.ListView, 20, ThumbnailOptions.UseCurrentScale);
                        _options.SetPropertyPrefetch(PropertyPrefetchOptions.BasicProperties, new string[] { "System.DateModified", "System.ContentType", "System.ItemPathDisplay", "System.Size", "System.FileExtension" });
                    }
                    else if (_pageName.Contains("Photo"))
                    {
                        _options.SetThumbnailPrefetch(ThumbnailMode.PicturesView, 275, ThumbnailOptions.ResizeThumbnail);
                        _options.SetPropertyPrefetch(PropertyPrefetchOptions.BasicProperties, new string[] { "System.FileExtension" });
                    }
                    _options.IndexerOption = IndexerOption.UseIndexerWhenAvailable;
                    break;
                }

                SortEntry sort = new SortEntry()
                {
                    PropertyName   = "System.FileName",
                    AscendingOrder = true
                };
                _options.SortOrder.Add(sort);
                if (!_rootFolder.AreQueryOptionsSupported(_options))
                {
                    _options.SortOrder.Clear();
                }

                uint index = 0;
                _folderQueryResult = _rootFolder.CreateFolderQueryWithOptions(_options);
                //_folderQueryResult.ContentsChanged += FolderContentsChanged;
                var numFolders = await _folderQueryResult.GetItemCountAsync();

                IReadOnlyList <StorageFolder> storageFolders = await _folderQueryResult.GetFoldersAsync(index, _step);

                while (storageFolders.Count > 0)
                {
                    foreach (StorageFolder folder in storageFolders)
                    {
                        if (tokenSourceCopy.IsCancellationRequested)
                        {
                            return;
                        }
                        await AddFolder(folder, _pageName, tokenSourceCopy.Token);
                    }
                    index         += _step;
                    storageFolders = await _folderQueryResult.GetFoldersAsync(index, _step);
                }

                index            = 0;
                _fileQueryResult = _rootFolder.CreateFileQueryWithOptions(_options);
                _fileQueryResult.ContentsChanged += FileContentsChanged;
                var numFiles = await _fileQueryResult.GetItemCountAsync();

                IReadOnlyList <StorageFile> storageFiles = await _fileQueryResult.GetFilesAsync(index, _step);

                while (storageFiles.Count > 0)
                {
                    foreach (StorageFile file in storageFiles)
                    {
                        if (tokenSourceCopy.IsCancellationRequested)
                        {
                            return;
                        }
                        await AddFile(file, _pageName, tokenSourceCopy.Token);
                    }
                    index       += _step;
                    storageFiles = await _fileQueryResult.GetFilesAsync(index, _step);
                }
                if (numFiles + numFolders == 0)
                {
                    TextState.isVisible = Visibility.Visible;
                }
                stopwatch.Stop();
                Debug.WriteLine("Loading of items in " + Universal.path + " completed in " + stopwatch.Elapsed.Seconds + " seconds.\n");
            }
            catch (UnauthorizedAccessException e)
            {
                if (path.Contains(@"C:\"))
                {
                    DisplayConsentDialog();
                }
                else
                {
                    MessageDialog unsupportedDevice = new MessageDialog("This device may be unsupported. Please file an issue report in Settings - About containing what device we couldn't access. Technical information: " + e, "Unsupported Device");
                    await unsupportedDevice.ShowAsync();

                    return;
                }
            }
            catch (COMException e)
            {
                Frame         rootFrame = Window.Current.Content as Frame;
                MessageDialog driveGone = new MessageDialog(e.Message, "Drive Unplugged");
                await driveGone.ShowAsync();

                rootFrame.Navigate(typeof(MainPage), new SuppressNavigationTransitionInfo());
                return;
            }

            if (!_pageName.Contains("Classic"))
            {
                PVIS.isVisible = Visibility.Collapsed;
            }

            PVIS.isVisible = Visibility.Collapsed;
        }