private QueryOptions GetPicturesQuery(StorageFolder folder) { QueryOptions picturesQuery = new QueryOptions() { FolderDepth = FolderDepth.Deep, ApplicationSearchFilter = "System.Security.EncryptionOwners:[]", IndexerOption = IndexerOption.OnlyUseIndexerAndOptimizeForIndexedProperties }; picturesQuery.FileTypeFilter.Add(".jpg"); picturesQuery.FileTypeFilter.Add(".gif"); string[] otherProperties = new string[] { SystemProperties.GPS.LatitudeDecimal, SystemProperties.GPS.LongitudeDecimal }; picturesQuery.SetPropertyPrefetch(PropertyPrefetchOptions.BasicProperties | PropertyPrefetchOptions.ImageProperties, otherProperties); SortEntry sortOrder = new SortEntry() { AscendingOrder = true, PropertyName = "System.FileName" }; picturesQuery.SortOrder.Add(sortOrder); if (!folder.AreQueryOptionsSupported(picturesQuery)) { picturesQuery.SortOrder.Clear(); } return(picturesQuery); }
async private void LoadMediaFiles() { try { StorageFolder mediaServerFolder = mediaServers[dmsSelect.SelectedIndex]; var queryOptions = new QueryOptions(); queryOptions.FolderDepth = FolderDepth.Deep; queryOptions.UserSearchFilter = "System.Kind:=video"; if (mediaServerFolder.AreQueryOptionsSupported(queryOptions)) { var queryFolder = mediaServerFolder.CreateFileQueryWithOptions(queryOptions); mediaFiles = await queryFolder.GetFilesAsync(0, 25); mediaSelect.Items.Clear(); if (mediaFiles.Count == 0) { rootPage.NotifyUser("No Media Files found ", NotifyType.StatusMessage); } else { foreach (StorageFile file in mediaFiles) { mediaSelect.Items.Add(file.DisplayName); } rootPage.NotifyUser("Media files retrieved", NotifyType.StatusMessage); } } else { List <StorageFile> lstMediaItems = new List <StorageFile>(); var countOfVideoFilesFound = await BrowseForVideoFiles(mediaServerFolder, lstMediaItems, 25); mediaFiles = lstMediaItems; if (countOfVideoFilesFound > 0) { rootPage.NotifyUser("Media files retrieved", NotifyType.StatusMessage); } else { rootPage.NotifyUser("No Media Files found ", NotifyType.StatusMessage); } } } catch (Exception e) { rootPage.NotifyUser("Error locating media files " + e.Message, NotifyType.ErrorMessage); } }
// 排序过滤文件夹和文件 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 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; }
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); } }
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; }