// Callback from the selection cache manager // Retrieves the keys for selected items private async Task <string[]> fetchSelectionDataCallback(ItemIndexRange batch, CancellationToken ct) { #if TRACE_DATASOURCE Debug.WriteLine("# SelectionDataCallback: " + batch.FirstIndex + "->" + batch.LastIndex); #endif // See if we already have the item in the data cache, if so get the key from there so we don't need to go to the filesystem var file = itemCache[batch.FirstIndex]; if (file != null) { return(new string[] { file.Key }); } // Go get the keys from the file system if necessary IReadOnlyList <StorageFile> results = await _queryResult.GetFilesAsync((uint)batch.FirstIndex, batch.Length).AsTask(ct); List <string> keys = new List <string>(); if (results != null) { for (int i = 0; i < results.Count; i++) { ct.ThrowIfCancellationRequested(); keys.Add(results[i].FolderRelativeId); } } return(keys.ToArray()); }
/// <summary> /// Add folder to Library asynchronously. /// </summary> /// <param name="queryResult">The query result after querying in a specific folder.</param> /// <returns></returns> public static async Task <IEnumerable <Mediafile> > GetSongsFromFolderAsync(StorageFolder folder, bool useIndexer = true, uint stepSize = 20) { StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(DirectoryWalker.GetQueryOptions(null, useIndexer)); uint index = 0; IReadOnlyList <StorageFile> files = await queryResult.GetFilesAsync(index, stepSize); index += stepSize; var count = await queryResult.GetItemCountAsync(); if (count <= 0) { BLogger.I("No songs found."); await SharedLogic.Instance.NotificationManager.ShowMessageAsync("No songs found! Please try again."); return(null); } var tempList = new List <Mediafile>((int)count); short progress = 0; try { // Note that I'm paging in the files as described while (files.Count != 0) { var fileTask = queryResult.GetFilesAsync(index, stepSize).AsTask(); for (int i = 0; i < files.Count; i++) { if (files[i]?.IsAvailable == true) { progress++; Messenger.Instance.NotifyColleagues(MessageTypes.MsgUpdateSongCount, progress); Mediafile mp3File = await TagReaderHelper.CreateMediafile(files[i], false).ConfigureAwait(false); //the core of the whole method. if (mp3File != null) { mp3File.FolderPath = Path.GetDirectoryName(files[i].Path); await SaveSingleFileAlbumArtAsync(mp3File, files[i]).ConfigureAwait(false); SharedLogic.Instance.NotificationManager.ShowStaticMessage(progress + "\\" + count + " Song(s) Loaded"); tempList.Add(mp3File); } } } files = await fileTask; index += stepSize; } } catch (Exception ex) { string message = ex.Message + "||" + ex.InnerException; BLogger.E("Error while importing folder.", ex); await SharedLogic.Instance.NotificationManager.ShowMessageAsync(message); } return(tempList.DistinctBy(f => f.OrginalFilename)); }
private async Task UpdatePicturesUsingIndexer(CancellationToken cancellationToken) { Stopwatch watch = Stopwatch.StartNew(); _allPictures.Clear(); //clear the result of previous operation QueryOptions options = new QueryOptions(CommonFileQuery.OrderByDate, new String[] { ".jpg", ".jpeg", ".png" }) { IndexerOption = IndexerOption.UseIndexerWhenAvailable }; options.SetPropertyPrefetch(PropertyPrefetchOptions.None, new String[] { "System.Size", "System.DateModified" }); // Set up thumbnail prefetch. const uint requestedSize = 190; const ThumbnailMode thumbnailMode = ThumbnailMode.PicturesView; const ThumbnailOptions thumbnailOptions = ThumbnailOptions.UseCurrentScale; options.SetThumbnailPrefetch(thumbnailMode, requestedSize, thumbnailOptions); StorageFileQueryResult queryResult = KnownFolders.PicturesLibrary.CreateFileQueryWithOptions(options); uint index = 0, stepSize = 10; IReadOnlyList <StorageFile> files = await queryResult.GetFilesAsync(index, stepSize); // Note that I'm paging in the files as described while (files.Count != 0) { foreach (StorageFile file in files) { IDictionary <string, object> props = await file.Properties.RetrievePropertiesAsync( new String[] { "System.Size", "System.DateModified" }); var thumbnail = await file.GetThumbnailAsync(thumbnailMode, requestedSize, thumbnailOptions); _allPictures.Add(new PictureFileInfo() { FileName = file.Name, FileSize = (ulong)props["System.Size"], DateModified = (DateTimeOffset)props["System.DateModified"], Thumbnail = thumbnail }); } //If a cancellation is requested, abort the operation. cancellationToken.ThrowIfCancellationRequested(); index += 10; var fileTask = queryResult.GetFilesAsync(index, stepSize).AsTask(); files = await fileTask; } Debug.WriteLine($"{_allPictures.Count} pictures are listed. Elapsed ms: {watch.ElapsedMilliseconds}"); }
public override Task <IList <StorageMedia> > LoadDataAsync() { return(Task.Run <IList <StorageMedia> >(async() => { using (await _loadMoreLock.WaitAsync()) { if (_query == null) { await KnownFolders.PicturesLibrary.TryGetItemAsync("yolo"); var queryOptions = new QueryOptions(CommonFileQuery.OrderByDate, Constants.MediaTypes); queryOptions.FolderDepth = FolderDepth.Deep; _query = KnownFolders.PicturesLibrary.CreateFileQueryWithOptions(queryOptions); _query.ContentsChanged += OnContentsChanged; _startIndex = 0; } var items = new List <StorageMedia>(); var result = await _query.GetFilesAsync(_startIndex, 10); _startIndex += (uint)result.Count; foreach (var file in result) { if (await StorageMedia.CreateAsync(file) is StorageMedia storage) { items.Add(storage); } } return items; } })); }
public async static Task AddStorageFilesToLibrary(StorageFileQueryResult queryResult) { foreach (var file in await queryResult.GetFilesAsync()) { Mediafile mp3file = null; int index = -1; if (file != null) { if (TracksCollection.Elements.Any(t => t.Path == file.Path)) { index = TracksCollection.Elements.IndexOf(TracksCollection.Elements.First(t => t.Path == file.Path)); RemoveMediafile(TracksCollection.Elements.First(t => t.Path == file.Path)); } //this methods notifies the Player that one song is loaded. We use both 'count' and 'i' variable here to report current progress. await NotificationManager.ShowAsync(" Song(s) Loaded", "Loading..."); await Task.Run(async() => { //here we load into 'mp3file' variable our processed Song. This is a long process, loading all the properties and the album art. mp3file = await SharedLogic.CreateMediafile(file, false); //the core of the whole method. await SaveSingleFileAlbumArtAsync(mp3file, file).ConfigureAwait(false); }); AddMediafile(mp3file, index); } } }
/// <summary> /// 指定フォルダ以下にある画像ファイルのみを抽出して返す /// </summary> /// <param name="folder"></param> /// <returns></returns> private async Task <IReadOnlyList <StorageFile> > getImageFilesAsync(StorageFolder folder) { QueryOptions queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, FileKind.GetImageFilterList()); StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(queryOptions); return(await queryResult.GetFilesAsync()); }
private async void FindGif() { List <string> fileTypeFilter = new List <string> { ".gif" }; var queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, fileTypeFilter) { ApplicationSearchFilter = "System.FileName:*\"" + Path.GetFileNameWithoutExtension(File.Name) + "\"*" }; StorageFolder folder = await File.GetParentAsync(); StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(queryOptions); var files = await queryResult.GetFilesAsync(); if (files.Count > 0) { IRandomAccessStream fileStream = await files[0].OpenAsync(FileAccessMode.Read); BitmapImage image = new BitmapImage(); image.SetSource(fileStream); Gif = image; } }
private async Task Create(FolderViewModel vm) { var sf = await vm.GetStorageFolderAsync(); var options = new QueryOptions { FolderDepth = FolderDepth.Deep, IndexerOption = IndexerOption.DoNotUseIndexer, ApplicationSearchFilter = ComposeFilters(), }; options.FileTypeFilter.AddRange(Statics.AudioFileTypes); Query = sf.CreateFileQueryWithOptions(options); // Event "ContentsChanged" only fires after GetFilesAsync has been called at least once. await Query.GetFilesAsync(); _subscription = Observable.FromEventPattern <TypedEventHandler <IStorageQueryResultBase, object>, object>( h => Query.ContentsChanged += h, h => Query.ContentsChanged -= h) //.SkipUntil(autoRefresh.Where(x => x == true)) //.TakeUntil(autoRefresh.Where(x => x == false)) //.Repeat() .Select(_ => Unit.Default) .Subscribe(_contentChanged); }
private async void LoadVideosFromFolder(StorageFolder selectedFolder) { if (selectedFolder != null) { // Clear old files. importingList.Clear(); // Filter to get video files only. List <string> fileTypeFilter = new List <string> { ".mp4", ".wmv", ".mkv", ".avi" }; QueryOptions queryOptions = new QueryOptions(CommonFileQuery.OrderByName, fileTypeFilter); StorageFileQueryResult results = selectedFolder.CreateFileQueryWithOptions(queryOptions); IReadOnlyList <StorageFile> fileList = await results.GetFilesAsync(); // Populate file list. foreach (StorageFile file in fileList) { importingList.Add(new VideoFile(file)); } StatusText.Text = "Loaded " + importingList.Count + " files."; } TextFileNum.Text = importingList.Count + " files"; }
private async void LoadFolder(StorageFolder selectedFolder) { if (selectedFolder != null) { // Clear old files. displayedFileList.Clear(); // Application now has read/write access to all contents in the picked folder (including other sub-folder contents). StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", selectedFolder); // Filter to get video files only. List <string> fileTypeFilter = new List <string> { ".mp4", ".wmv", ".mkv", ".avi" }; QueryOptions queryOptions = new QueryOptions(CommonFileQuery.OrderByName, fileTypeFilter); StorageFileQueryResult results = selectedFolder.CreateFileQueryWithOptions(queryOptions); IReadOnlyList <StorageFile> fileList = await results.GetFilesAsync(); // Populate file list. foreach (StorageFile file in fileList) { displayedFileList.Add(new VideoFile(file)); } } }
private async void ReadAllFiles() { // Get the app's installation folder. Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; // Get the files in the current folder. StorageFileQueryResult results = storageFolder.CreateFileQuery(); // Iterate over the results and print the list of files // to the Visual Studio Output window. IReadOnlyList <StorageFile> filesInFolder = await results.GetFilesAsync(); foreach (StorageFile item in filesInFolder) { TextBlock tb = new TextBlock(); tb.Text = item.Name; StackPanel sp = new StackPanel(); sp.Tag = item.Name; sp.Orientation = Orientation.Vertical; sp.Tapped += Sp_Tapped; sp.Children.Add(tb); outerWrapper.Children.Add(sp); } }
async void LoadStudentDetails() { // Check to see if file exists //Get local storage folder StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; //create a file query StorageFileQueryResult fileResults = storageFolder.CreateFileQuery(); //Get all files in the directory IReadOnlyList <StorageFile> fileList = await fileResults.GetFilesAsync(); //check to see if we have a file studentsFile = fileList.SingleOrDefault(file => file.Name == "students.txt"); if (studentsFile == null) { //if not create studentsFile = await storageFolder.CreateFileAsync("students.txt"); } else { //else load from a stream using (StreamReader reader = new StreamReader(await studentsFile.OpenStreamForReadAsync())) { while (!reader.EndOfStream) { string line = reader.ReadLine(); Student student = new Student(); student.parse(line); RegisteredStudents.Add(student); } } } }
private async void Find_Click(object sender, RoutedEventArgs e) { ContentTextOutput.Text = ""; List <string> propertyNames = new List <string>(); propertyNames.Add("System.FileName"); var queryOptions = new Windows.Storage.Search.QueryOptions(); queryOptions.IndexerOption = Windows.Storage.Search.IndexerOption.OnlyUseIndexer; queryOptions.UserSearchFilter = FindQueryText.Text; queryOptions.SetPropertyPrefetch(Windows.Storage.FileProperties.PropertyPrefetchOptions.DocumentProperties, propertyNames); // Query the Pictures library. StorageFileQueryResult queryResult = Windows.Storage.KnownFolders.PicturesLibrary.CreateFileQueryWithOptions(queryOptions); IReadOnlyList <StorageFile> files = await queryResult.GetFilesAsync(); foreach (StorageFile file in files) { IDictionary <String, IReadOnlyList <Windows.Data.Text.TextSegment> > fileRangeProperties = queryResult.GetMatchingPropertiesWithRanges(file); if (fileRangeProperties.ContainsKey("System.FileName")) { IReadOnlyList <Windows.Data.Text.TextSegment> ranges; fileRangeProperties.TryGetValue("System.FileName", out ranges); rootPage.HighlightRanges(ContentTextOutput, file.DisplayName, ranges); } // Note: You can continue looking for other properties you would like to highlight on the file here. } if (files.Count == 0) { ContentTextOutput.Text = "There were no matching files in your Pictures Library"; } }
public static async Task <List <string> > GetMatchingFilesByPrefixAsync(string prefix, List <string> excludeFiles) { try { List <string> result = new List <string>(); var folder = ApplicationData.Current.LocalFolder; QueryOptions queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, new List <string>() { "*" }); queryOptions.UserSearchFilter = $"{prefix}*.*"; queryOptions.FolderDepth = FolderDepth.Shallow; queryOptions.IndexerOption = IndexerOption.UseIndexerWhenAvailable; StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(queryOptions); IReadOnlyList <StorageFile> matchingFiles = await queryResult.GetFilesAsync(); if (matchingFiles.Count > 0) { result.AddRange( matchingFiles.Where(f => !excludeFiles.Contains(f.Name)).Select(f => f.Name) ); } return(result); } catch (Exception ex) { Debug.WriteLine(ex); } return(null); }
public void LoadContent(StorageFolder folder) { Thumbnails.Clear(); List <string> fileTypeFilter = new List <string>(); fileTypeFilter.Add(".jpg"); fileTypeFilter.Add(".jpeg"); fileTypeFilter.Add(".png"); fileTypeFilter.Add(".bmp"); QueryOptions queryOptions = new QueryOptions(CommonFileQuery.OrderBySearchRank, fileTypeFilter); Task.Run(async() => { StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(queryOptions); var files = await queryResult.GetFilesAsync(); foreach (var file in files) { if (IsImageFile(file)) { await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Thumbnails.Add(new ImageViewerItem(file)); }); } } }); }
/// <summary> /// This is the click handler for the button that represents a user. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> async private void UserButton_Click(object sender, RoutedEventArgs e) { Button b = sender as Button; if (b != null) { OutputProgressRing.IsActive = true; // Get the folder that represents the user's files, which wwe saved as the DataContext. StorageFolder folder = (StorageFolder)b.DataContext; // This try/catch block is for scenarios where the HomeGroup Known Folder is not available. try { // Search for all files in that folder. QueryOptions queryOptions = new QueryOptions(CommonFileQuery.OrderBySearchRank, null); queryOptions.UserSearchFilter = "*"; StorageFileQueryResult queryResults = folder.CreateFileQueryWithOptions(queryOptions); IReadOnlyList <StorageFile> files = await queryResults.GetFilesAsync(); string outputString = string.Format("Files shared by {0}: {1}\n", folder.Name, files.Count); foreach (StorageFile file in files) { outputString += file.Name + "\n"; } rootPage.NotifyUser(outputString, NotifyType.StatusMessage); } catch (Exception ex) { rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage); } OutputProgressRing.IsActive = false; } }
/// <summary> /// Gets all the pictures from the Local state storage folder /// </summary> /// <returns></returns> public async Task GetAllPictures() { // Set options for file type List <string> fileTypeFilter = new List <string>(); fileTypeFilter.Add(".jpg"); fileTypeFilter.Add(".png"); QueryOptions queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, fileTypeFilter); StorageFileQueryResult results = Helper.storageFolder.CreateFileQueryWithOptions(queryOptions); //Get all the pictures asynchronously IReadOnlyList <StorageFile> files = await results.GetFilesAsync(); foreach (StorageFile file in files) { //Get thumbnail for the fetched picture var thumb = await file.GetThumbnailAsync(thumbnailMode, size); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(thumb); var pic = new Picture() { picName = file.Name, albumName = null, path = file.Path, dateAdded = file.DateCreated.LocalDateTime, picThumbnail = bitmapImage }; //add to observable collection allPicsList.Add(pic); } }
public static async Task<IReadOnlyList<StorageFile>> GetFilesInFolder(List<string> fileTypeFilter, StorageFolder folder) { if (folder == null || fileTypeFilter == null || fileTypeFilter.Count == 0) { return null; } else { try { QueryOptions queryOptions = new QueryOptions(); foreach (var item in fileTypeFilter) { if (item.IndexOf(".") == 0) { queryOptions.FileTypeFilter.Add(item); } else { continue; } } StorageFileQueryResult results = folder.CreateFileQueryWithOptions(queryOptions); return await results.GetFilesAsync(); } catch (IOException) { return null; } catch (UnauthorizedAccessException) { return null; } } }
async void GetProfilePicAsync() { string profilePicPlaceholderPath = "ms-appx:///Assets/StoreLogo.scale-400.png"; ProfilePic = new BitmapImage(new Uri(profilePicPlaceholderPath)); ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; if (localSettings.Values["PerformerImageFolder"] is string token) { StorageItemAccessList futureAccessList = StorageApplicationPermissions.FutureAccessList; StorageFolder profilePicFolder = await futureAccessList.GetFolderAsync(token); List <string> fileTypeFilter = new List <string> { ".jpg" }; var queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, fileTypeFilter) { ApplicationSearchFilter = "System.FileName:*\"" + Name + "\"*" }; StorageFileQueryResult queryResult = profilePicFolder.CreateFileQueryWithOptions(queryOptions); var files = await queryResult.GetFilesAsync(); if (files.Count > 0) { BitmapImage screen = new BitmapImage(); screen.SetSource(await files[0].GetThumbnailAsync(ThumbnailMode.SingleItem)); ProfilePic = screen; } } }
private async Task LoadPicturesFromAlbums() { //Ordering album files by date // initialize queryOptions using a common query QueryOptions queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, new string[] { ".txt" }); // clear all existing sorts queryOptions.SortOrder.Clear(); // add ascending sort by date modified SortEntry se = new SortEntry(); se.PropertyName = "System.DateModified"; se.AscendingOrder = true; queryOptions.SortOrder.Add(se); //Open folder containing album files var storageFolder = ApplicationData.Current.LocalFolder; //Use query to sort album data text files by date StorageFileQueryResult queryResult = storageFolder.CreateFileQueryWithOptions(queryOptions); IReadOnlyList <StorageFile> textFiles = await queryResult.GetFilesAsync(); foreach (var textFile in textFiles) { if (textFile.Name != "Library.txt") { await dynamicControlAsync(textFile.Name); } } }
public static async Task <bool> CheckIfNeedToUpdate() { try { QueryOptions Options = new QueryOptions { ApplicationSearchFilter = "System.FileName:BingDailyPicture_Cache*", FolderDepth = FolderDepth.Shallow, IndexerOption = IndexerOption.UseIndexerWhenAvailable }; StorageFileQueryResult QueryResult = ApplicationData.Current.TemporaryFolder.CreateFileQueryWithOptions(Options); IReadOnlyList <StorageFile> AllPreviousPictureList = await QueryResult.GetFilesAsync(); if (AllPreviousPictureList.All((Item) => DateTime.TryParseExact(Regex.Match(Item.Name, @"(?<=\[)(.+)(?=\])").Value, "yyyy-MM-dd HH-mm-ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out DateTime LastUpdateDate) && LastUpdateDate < DateTime.Now.Date)) { foreach (StorageFile ToDelete in AllPreviousPictureList) { await ToDelete.DeleteAsync(StorageDeleteOption.PermanentDelete); } return(true); } else { return(false); } }
public async Task <IEnumerable <StorageFile> > GetStorageFilesInFolderAsync(StorageFolder folder) { //Get query options with which we search for files in the specified folder var options = DirectoryWalker.GetQueryOptions(); /* * options.FileTypeFilter.Add(".mp3"); * options.FileTypeFilter.Add(".wav"); * options.FileTypeFilter.Add(".ogg"); * options.FileTypeFilter.Add(".flac"); * options.FileTypeFilter.Add(".m4a"); * options.FileTypeFilter.Add(".aif"); * options.FileTypeFilter.Add(".wma");*/ //this is the query result which we recieve after querying in the folder StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(options); //'count' is for total files got after querying. uint count = await queryResult.GetItemCountAsync(); //the event for files changed queryResult.ContentsChanged += QueryResult_ContentsChanged; if (count == 0) { string error = "No songs found!"; BLogger.Logger.Error("No songs were found!"); await SharedLogic.NotificationManager.ShowMessageAsync(error); return(null); } return(await queryResult.GetFilesAsync()); }
/// <summary> /// 扫描本地Music Library的所有音乐 /// </summary> /// <returns>返回所有的音乐文件属性和相对music library的路径</returns> public static async Task <List <MusicPropertiesWithPath> > ScanLocalMusicInLibrary() { StorageFolder folder = KnownFolders.MusicLibrary; List <MusicPropertiesWithPath> songs = new List <MusicPropertiesWithPath>(); StorageFileQueryResult query = folder.CreateFileQuery(CommonFileQuery.OrderByMusicProperties); //var files = await folder.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByMusicProperties); var files = await query.GetFilesAsync(); foreach (var file in files) { var properties = await file.Properties.GetMusicPropertiesAsync(); try { using (var stream = await file.OpenReadAsync()) { songs.Add(new MusicPropertiesWithPath() { DefinedProperties = properties, FileName = file.Path.Substring(file.Path.IndexOf("Music")).Remove(0, 6) }); } } catch (Exception ex) { } } return(songs); }
public async Task GetAppFiles(string searchKey) { try { List <string> fileTypeFilter = new List <string> { searchKey }; QueryOptions queryOptions = new QueryOptions(CommonFileQuery.OrderByName, fileTypeFilter); StorageFileQueryResult queryResult = this.SearchedDirectory.CreateFileQueryWithOptions(queryOptions); var files = await queryResult.GetFilesAsync(); foreach (var file in files) { var copyTo = Path.Combine(this.OutputDirectory, file.Name); await file.CopyAsync(this.folder, file.DisplayName, NameCollisionOption.ReplaceExisting); } } catch (Exception e) when(e is IOException || e is UnauthorizedAccessException || e is ArgumentException) { throw; } }
private async Task <bool> MonitorConfigFile() { bool retVal = true; try { // Watch for all ".xml" files (there is only the config.xml file in this app's data folder) // And add a handler for when the folder contents change var fileTypeQuery = new List <string>(); fileTypeQuery.Add(".xml"); var options = new Windows.Storage.Search.QueryOptions(Windows.Storage.Search.CommonFileQuery.DefaultQuery, fileTypeQuery); _query = ApplicationData.Current.LocalFolder.CreateFileQueryWithOptions(options); _query.ContentsChanged += FolderContentsChanged; // Start Monitoring. The first time this is called (after starting the query) we want to ignore the notification _bIgnoreFirstChangeNotification = true; var files = await _query.GetFilesAsync(); } catch (Exception /*ex*/) { retVal = false; } return(retVal); }
public static async Task <IReadOnlyList <Picture> > GetPicturesByAlbum(string albumName) { StorageFolder storageFolder = ApplicationData.Current.LocalFolder; var allPicsList = new List <Picture>(); // Set options for file type and sort order. List <string> fileTypeFilter = new List <string>(); fileTypeFilter.Add(".jpg"); fileTypeFilter.Add(".png"); QueryOptions queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, fileTypeFilter); // Get the JPG files in the user's Pictures folder // and its subfolders and sort them by date. StorageFileQueryResult results = storageFolder.CreateFileQueryWithOptions(queryOptions); IReadOnlyList <StorageFile> files = await results.GetFilesAsync(); foreach (StorageFile file in files.OrderBy(a => a.DateCreated)) { var pic = new Picture() { picName = file.Name, albumName = null, path = file.Path, dateAdded = file.DateCreated.LocalDateTime }; allPicsList.Add(pic); } return(allPicsList); }
public async Task <IReadOnlyList <StorageFile> > GetFilesAsync(List <string> fileTypes) { QueryOptions queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, fileTypes); StorageFileQueryResult queryResult = _storage.CreateFileQueryWithOptions(queryOptions); IReadOnlyList <StorageFile> files = await queryResult.GetFilesAsync(); return(files); }
private async static Task <IReadOnlyList <IStorageItem> > EnumerateFileQuery(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { // Get a StorageFolder for "path" string fullPath = Path.GetFullPath(path); StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(fullPath).TranslateWinRTTask(fullPath, isDirectory: true); // Construct a query for the search. QueryOptions query = new QueryOptions(); // Translate SearchOption into FolderDepth query.FolderDepth = searchOption == SearchOption.AllDirectories ? FolderDepth.Deep : FolderDepth.Shallow; // Construct an AQS filter string normalizedSearchPattern = PathHelpers.NormalizeSearchPattern(searchPattern); if (normalizedSearchPattern.Length == 0) { // An empty searchPattern will return no results and requires no AQS parsing. return(new IStorageItem[0]); } else { // Parse the query as an ItemPathDisplay filter. string searchPath = PathHelpers.GetFullSearchString(fullPath, normalizedSearchPattern); string aqs = "System.ItemPathDisplay:~\"" + searchPath + "\""; query.ApplicationSearchFilter = aqs; // If the filtered path is deeper than the given user path, we need to get a new folder for it. // This occurs when someone does something like Enumerate("C:\first\second\", "C:\first\second\third\*"). // When AllDirectories is set this isn't an issue, but for TopDirectoryOnly we have to do some special work // to make sure something is actually returned when the searchPattern is a subdirectory of the path. // To do this, we attempt to get a new StorageFolder for the subdirectory and return an empty enumerable // if we can't. string searchPatternDirName = Path.GetDirectoryName(normalizedSearchPattern); string userPath = string.IsNullOrEmpty(searchPatternDirName) ? fullPath : Path.Combine(fullPath, searchPatternDirName); if (userPath != folder.Path) { folder = await StorageFolder.GetFolderFromPathAsync(userPath).TranslateWinRTTask(userPath, isDirectory: true); } } // Execute our built query if (searchTarget == SearchTarget.Files) { StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(query); return(await queryResult.GetFilesAsync().TranslateWinRTTask(folder.Path, isDirectory: true)); } else if (searchTarget == SearchTarget.Directories) { StorageFolderQueryResult queryResult = folder.CreateFolderQueryWithOptions(query); return(await queryResult.GetFoldersAsync().TranslateWinRTTask(folder.Path, isDirectory: true)); } else { StorageItemQueryResult queryResult = folder.CreateItemQueryWithOptions(query); return(await queryResult.GetItemsAsync().TranslateWinRTTask(folder.Path, isDirectory: true)); } }
public async Task <ulong> GetFolderSizeAsync(CancellationToken CancelToken = default) { if (WIN_Native_API.CheckLocationAvailability(Path)) { return(await Task.Run(() => { return WIN_Native_API.CalulateSize(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.UseIndexerWhenAvailable }; Options.SetPropertyPrefetch(Windows.Storage.FileProperties.PropertyPrefetchOptions.BasicProperties, new string[] { "System.Size" }); StorageFileQueryResult Query = Folder.CreateFileQueryWithOptions(Options); uint FileCount = await Query.GetItemCountAsync(); ulong TotalSize = 0; for (uint Index = 0; Index < FileCount && !CancelToken.IsCancellationRequested; Index += 50) { foreach (StorageFile File in await Query.GetFilesAsync(Index, 50)) { TotalSize += await File.GetSizeRawDataAsync().ConfigureAwait(false); if (CancelToken.IsCancellationRequested) { break; } } } return(TotalSize); } else { return(0); } } catch (Exception ex) { LogTracer.Log(ex, $"{nameof(GetFolderSizeAsync)} failed for uwp API"); return(0); } } }
private async void ItemQuery_ContentsChanged(IStorageQueryResultBase sender, object args) { if (refreshRunning) { return; } refreshRunning = true; //itemQuery.ApplyNewQueryOptions(new QueryOptions()); var items = await fileQuery.GetFilesAsync(); await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { await AddDifference(items, browseCts.Token); }); refreshRunning = false; }