Example #1
0
        /// <summary>
        /// This is the click handler for the Search button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void Search_Click(object sender, RoutedEventArgs e)
        {
            OutputProgressRing.IsActive = true;
            Windows.Storage.Search.QueryOptions queryOptions = new Windows.Storage.Search.QueryOptions(Windows.Storage.Search.CommonFileQuery.OrderBySearchRank, null);
            queryOptions.UserSearchFilter = QueryInputBox.Text;

            // This try/catch block is for scenarios where the Homegroup Known Folder is not available.
            try
            {
                Windows.Storage.Search.StorageFileQueryResult queryResults = Windows.Storage.KnownFolders.HomeGroup.CreateFileQueryWithOptions(queryOptions);
                System.Collections.Generic.IReadOnlyList<Windows.Storage.StorageFile> files = await queryResults.GetFilesAsync();

                if (files.Count > 0)
                {
                    string outputString = (files.Count == 1) ? "One file found\n\n" : files.Count.ToString() + " files found\n\n";
                    foreach (Windows.Storage.StorageFile file in files)
                    {
                        outputString += file.Name + "\n";
                    }
                    rootPage.NotifyUser(outputString, NotifyType.StatusMessage);
                }
                else
                {
                    rootPage.NotifyUser("No files found.", NotifyType.StatusMessage);
                }
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
            }
            OutputProgressRing.IsActive = false;
        }
Example #2
0
        public static async Task <IReadOnlyList <StorageFile> > ReadFilesAsync(IReadOnlyList <IStorageItem> p)
        {
            var list = new List <StorageFile>();

            foreach (var item in p)
            {
                if (item is IStorageFile file)
                {
                    foreach (var types in Consts.FileTypes)
                    {
                        if (types == file.FileType)
                        {
                            list.Add(file as StorageFile);
                            break;
                        }
                    }
                }
                else if (item is StorageFolder folder)
                {
                    var options = new Windows.Storage.Search.QueryOptions
                    {
                        FileTypeFilter = { ".flac", ".wav", ".m4a", ".aac", ".mp3", ".wma", ".ogg", ".oga" },
                        FolderDepth    = Windows.Storage.Search.FolderDepth.Deep,
                        IndexerOption  = Windows.Storage.Search.IndexerOption.DoNotUseIndexer,
                    };
                    var query = folder.CreateFileQueryWithOptions(options);
                    list.AddRange(await query.GetFilesAsync());
                }
            }
            return(list);
        }
Example #3
0
        /// <summary>
        /// This is the click handler for the Search button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void Search_Click(object sender, RoutedEventArgs e)
        {
            OutputProgressRing.IsActive = true;
            Windows.Storage.Search.QueryOptions queryOptions = new Windows.Storage.Search.QueryOptions(Windows.Storage.Search.CommonFileQuery.OrderBySearchRank, null);
            queryOptions.UserSearchFilter = QueryInputBox.Text;

            // This try/catch block is for scenarios where the Homegroup Known Folder is not available.
            try
            {
                Windows.Storage.Search.StorageFileQueryResult queryResults = Windows.Storage.KnownFolders.HomeGroup.CreateFileQueryWithOptions(queryOptions);
                System.Collections.Generic.IReadOnlyList <Windows.Storage.StorageFile> files = await queryResults.GetFilesAsync();

                if (files.Count > 0)
                {
                    string outputString = (files.Count == 1) ? "One file found\n\n" : files.Count.ToString() + " files found\n\n";
                    foreach (Windows.Storage.StorageFile file in files)
                    {
                        outputString += file.Name + "\n";
                    }
                    rootPage.NotifyUser(outputString, NotifyType.StatusMessage);
                }
                else
                {
                    rootPage.NotifyUser("No files found.", NotifyType.StatusMessage);
                }
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
            }
            OutputProgressRing.IsActive = false;
        }
Example #4
0
        public static async Task <List <StorageFile> > FindChanges()
        {
            var opr       = SQLOperator.Current();
            var filePaths = await opr.GetFilePathsAsync();

            var foldersDB = await opr.GetAllAsync <FOLDER>();

            var folders = FileReader.InitFolderList();

            foreach (var f in foldersDB)
            {
                StorageFolder folder = await f.GetFolderAsync();

                if (folders.Exists(a => a.Path == folder.Path))
                {
                    continue;
                }
                folders.Add(folder);
            }
            var list = new List <StorageFile>();

            foreach (var item in folders)
            {
                if (item == null)
                {
                    continue;
                }
                var options = new Windows.Storage.Search.QueryOptions
                {
                    FileTypeFilter = { ".flac", ".wav", ".m4a", ".aac", ".mp3" },
                    FolderDepth    = Windows.Storage.Search.FolderDepth.Deep,
                    IndexerOption  = Windows.Storage.Search.IndexerOption.DoNotUseIndexer,
                };
                var query = item.CreateFileQueryWithOptions(options);
                var files = await query.GetFilesAsync();

                list.AddRange(files);
                var t = Task.Run(async() => { await opr.UpdateFolderAsync(item, files.Count); });
            }
            list.Distinct(new StorageFileComparer());

            foreach (var path in filePaths)
            {
                try
                {
                    var file = await StorageFile.GetFileFromPathAsync(path);

                    if (list.Find(x => x.Path == file.Path) is StorageFile f)
                    {
                        list.Remove(f);
                    }
                }
                catch (FileNotFoundException)
                {
                    await opr.RemoveSongAsync(path);
                }
            }
            return(list);
        }
Example #5
0
        /// <summary>
        /// This is the click handler for all four buttons in this example.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void Default_Click(object sender, RoutedEventArgs e)
        {
            Button b = sender as Button;

            if (b != null)
            {
                OutputProgressRing.IsActive = true;

                // Each visible button was previously set to display a homegroup user's name
                string userName = b.Content.ToString();

                // This try/catch block is for scenarios where the Homegroup Known Folder is not available.
                try
                {
                    System.Collections.Generic.IReadOnlyList <Windows.Storage.StorageFolder> hgFolders = await Windows.Storage.KnownFolders.HomeGroup.GetFoldersAsync();

                    bool userFound = false;

                    foreach (Windows.Storage.StorageFolder folder in hgFolders)
                    {
                        if (folder.DisplayName == userName)
                        {
                            // We've found the folder belonging to the target user; search for all files under it
                            userFound = true;
                            Windows.Storage.Search.QueryOptions queryOptions = new Windows.Storage.Search.QueryOptions(Windows.Storage.Search.CommonFileQuery.OrderBySearchRank, null);
                            queryOptions.UserSearchFilter = "*";
                            Windows.Storage.Search.StorageFileQueryResult queryResults = folder.CreateFileQueryWithOptions(queryOptions);
                            System.Collections.Generic.IReadOnlyList <Windows.Storage.StorageFile> files = await queryResults.GetFilesAsync();

                            if (files.Count > 0)
                            {
                                string outputString = (files.Count == 1) ? "One file found\n\n" : files.Count.ToString() + " files found\n\n";
                                foreach (Windows.Storage.StorageFile file in files)
                                {
                                    outputString += file.Name + "\n";
                                }
                                rootPage.NotifyUser(outputString, NotifyType.StatusMessage);
                            }
                            else
                            {
                                rootPage.NotifyUser("No files found.", NotifyType.StatusMessage);
                            }
                        }
                    }

                    if (!userFound)
                    {
                        rootPage.NotifyUser("The user " + userName + " was not found on the HomeGroup.", NotifyType.ErrorMessage);
                    }
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
                }
                OutputProgressRing.IsActive = false;
            }
        }
 /// <summary>
 /// This function retrieves all items added to the index through the app's appcontent-ms files which
 /// have an ItemNameDisplay property containing "Sample 1"
 /// </summary>
 private void RetrieveMatchedItems_Click(object sender, RoutedEventArgs e)
 {
     var queryOptions = new Windows.Storage.Search.QueryOptions();
     // Include only items returned via the index in the search results
     queryOptions.IndexerOption = Windows.Storage.Search.IndexerOption.OnlyUseIndexer;
     // Create an AQS (Advanced Query Syntax) query which will look for ItemNameDisplay properties which contain "Sample 1"
     queryOptions.ApplicationSearchFilter = Windows.Storage.SystemProperties.ItemNameDisplay + ":\"Sample 1\"";
     RetrieveAppContentHelper(folder => folder.CreateFileQueryWithOptions(queryOptions));
 }
        /// <summary>
        /// This function retrieves all items added to the index through the app's appcontent-ms files which
        /// have an ItemNameDisplay property containing "Sample 1"
        /// </summary>
        private void RetrieveMatchedItems_Click(object sender, RoutedEventArgs e)
        {
            var queryOptions = new Windows.Storage.Search.QueryOptions();

            // Include only items returned via the index in the search results
            queryOptions.IndexerOption = Windows.Storage.Search.IndexerOption.OnlyUseIndexer;
            // Create an AQS (Advanced Query Syntax) query which will look for ItemNameDisplay properties which contain "Sample 1"
            queryOptions.ApplicationSearchFilter = Windows.Storage.SystemProperties.ItemNameDisplay + ":\"Sample 1\"";
            RetrieveAppContentHelper(folder => folder.CreateFileQueryWithOptions(queryOptions));
        }
Example #8
0
        public async Task <IReadOnlyList <StorageFile> > SearchFolder()
        {
            var options = new Windows.Storage.Search.QueryOptions
            {
                FileTypeFilter = { ".flac", ".wav", ".m4a", ".aac", ".mp3", ".wma" },
                FolderDepth    = Windows.Storage.Search.FolderDepth.Deep,
                IndexerOption  = Windows.Storage.Search.IndexerOption.DoNotUseIndexer,
            };
            var query = Folder.CreateFileQueryWithOptions(options);

            query.ContentsChanged += QueryContentsChanged;

            return(await query.GetFilesAsync());
        }
Example #9
0
        public static async Task <string> GetBuiltInArtworkAsync(string id, string name, StorageFile file)
        {
            if (id == "0")
            {
                id = CreateHash64(name).ToString();
            }
            var options = new Windows.Storage.Search.QueryOptions(Windows.Storage.Search.CommonFileQuery.DefaultQuery, new string[] { ".jpg", ".png", ".bmp" })
            {
                ApplicationSearchFilter = $"System.FileName:{id}.*"
            };

            var query = ApplicationData.Current.TemporaryFolder.CreateFileQueryWithOptions(options);
            var files = await query.GetFilesAsync();

            if (files.Count > 0)
            {
                return(files[0].Path);
            }
            else
            {
                using (var tag = TagLib.File.Create(file))
                {
                    var pictures = tag.Tag.Pictures;
                    if (!pictures.IsNullorEmpty())
                    {
                        var fileName = $"{id}.{pictures[0].MimeType.Split('/').LastOrDefault().Replace("jpeg", "jpg")}";
                        var s        = await ApplicationData.Current.TemporaryFolder.TryGetItemAsync(fileName);

                        if (s == null)
                        {
                            var cacheImg = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

                            await FileIO.WriteBytesAsync(cacheImg, pictures[0].Data.Data);

                            return(cacheImg.Path);
                        }
                        else
                        {
                            return(s.Path);
                        }
                    }
                    else
                    {
                        return(string.Empty);
                    }
                }
            }
        }
Example #10
0
        public static async Task <ulong> FolderSize(this StorageFolder folder)
        {
            var options = new Windows.Storage.Search.QueryOptions
            {
                FolderDepth = Windows.Storage.Search.FolderDepth.Deep,
            };
            var query = folder.CreateFileQueryWithOptions(options);

            var files = await query.GetFilesAsync();

            ulong si = 0ul;

            foreach (var file in files)
            {
                si += (await file.GetBasicPropertiesAsync()).Size;
            }

            return(si);
        }
Example #11
0
        /// <summary>
        /// returns a list of filenames for the
        /// specified directory.
        /// </summary>
        /// <param name="directoryPath"></param>
        /// <returns></returns>
        public async Task <List <string> > GetFileNames(string directoryPath, string pattern)
        {
            List <string> listFile       = new List <string>();
            List <string> fileTypeFilter = new List <string>();

            fileTypeFilter.Add(pattern);

            Windows.Storage.Search.QueryOptions queryOptions = new Windows.Storage.Search.QueryOptions(Windows.Storage.Search.CommonFileQuery.OrderBySearchRank, fileTypeFilter);
            queryOptions.UserSearchFilter = directoryPath;
            var fileQuery = applicationData.LocalFolder.CreateFileQueryWithOptions(queryOptions);

            var list = await fileQuery.GetFilesAsync();

            if (list != null)
            {
                foreach (var file in list)
                {
                    listFile.Add(file.Path);
                }
            }
            return(listFile);
        }
Example #12
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var library      = Windows.Storage.KnownFolders.PicturesLibrary;
            var queryOptions = new Windows.Storage.Search.QueryOptions();

            queryOptions.FolderDepth   = Windows.Storage.Search.FolderDepth.Deep;
            queryOptions.IndexerOption = Windows.Storage.Search.IndexerOption.UseIndexerWhenAvailable;

            var fileQuery = library.CreateFileQueryWithOptions(queryOptions);

            var fif = new Windows.Storage.BulkAccess.FileInformationFactory(
                fileQuery,
                Windows.Storage.FileProperties.ThumbnailMode.PicturesView,
                190,
                Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale,
                false
                );

            var dataSource = fif.GetVirtualizedFilesVector();

            this.PicturesListView.ItemsSource = dataSource;
        }
        /* 显示文件夹下视频的辅助函数 */
        private async void showVideoInFolder(string token)
        {
            var folder = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFolderAsync(token);

            if (folder != null)
            {
                var foldersQuery = folder.CreateFolderQuery();

                var filesQuery = new Windows.Storage.Search.QueryOptions();
                filesQuery.FileTypeFilter.Add(".mp4");
                filesQuery.FileTypeFilter.Add(".wma");
                filesQuery.FileTypeFilter.Add(".avi");

                var query = folder.CreateFileQueryWithOptions(filesQuery);
                var files = await query.GetFilesAsync();

                foreach (var file in files)
                {
                    //bitmapImage.SetSource(randomAccessStream);
                    BitmapImage bitmapImage = await Common.GetThumbnailOfVideo(file);

                    Video temp = await viewModel.Search(file.Path);

                    string videoToken;
                    string date = DateTimeOffset.Now.Year.ToString() + "/" + DateTimeOffset.Now.Month.ToString() + "/" + DateTimeOffset.Now.Day.ToString();
                    if (temp == null)
                    {
                        videoToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file);
                        videos.Add(new Video(videoToken, file.Name, date, "", 0, 0, 0, 0, file.Path, bitmapImage));
                    }
                    else
                    {
                        temp.Date = date;
                        videos.Add(temp);
                    }
                }
            }
        }
        private async Task <int> GetNumInFolder(StorageFolder folder)
        {
            int total         = 0;
            var foldersQuery  = folder.CreateFolderQuery();
            var listOfFolders = await foldersQuery.GetFoldersAsync();

            total += listOfFolders.Count;
            // get the num of folders

            // find mp4, wma, avi vedios
            var filesQueryOptions = new Windows.Storage.Search.QueryOptions();

            filesQueryOptions.FileTypeFilter.Add(".mp4");
            filesQueryOptions.FileTypeFilter.Add(".wma");
            filesQueryOptions.FileTypeFilter.Add(".avi");

            var listOfVideos = await folder.CreateFileQueryWithOptions(filesQueryOptions).GetFilesAsync();

            total += listOfVideos.Count;
            // get the num of videos

            return(total);
        }
Example #15
0
        public async void GetPicture()
        {
            StorageFile fileLocal = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appdata:///local/account/" + ImageHelper.folderStr + ".json"));

            if (fileLocal != null)
            {
                try
                {
                    //读取本地文件内容,并且反序列化
                    using (IRandomAccessStream readStream = await fileLocal.OpenAsync(FileAccessMode.Read))
                    {
                        using (DataReader dataReader = new DataReader(readStream))
                        {
                            UInt64 size = readStream.Size;
                            if (size <= UInt32.MaxValue)
                            {
                                await dataReader.LoadAsync(sizeof(Int32));

                                Int32 stringSize = dataReader.ReadInt32();
                                await dataReader.LoadAsync((UInt32)stringSize);

                                string        fileContent = dataReader.ReadString((uint)stringSize);
                                ImagePath     imagePath   = new ImagePath(fileContent);
                                StorageFolder folder      = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(imagePath.Path);

                                //筛选图片
                                var queryOptions = new Windows.Storage.Search.QueryOptions();
                                queryOptions.FileTypeFilter.Add(".png");
                                queryOptions.FileTypeFilter.Add(".jpg");
                                queryOptions.FileTypeFilter.Add(".bmp");
                                var query = folder.CreateFileQueryWithOptions(queryOptions);
                                var files = await query.GetFilesAsync();

                                ImagePath img;
                                var       imgList = new ObservableCollection <ImagePath>();
                                foreach (var item in files)
                                {
                                    IRandomAccessStream irandom = await item.OpenAsync(FileAccessMode.Read);

                                    //对图像源使用流源
                                    BitmapImage bitmapImage = new BitmapImage();
                                    bitmapImage.DecodePixelWidth  = 160;
                                    bitmapImage.DecodePixelHeight = 100;
                                    await bitmapImage.SetSourceAsync(irandom);

                                    img         = new ImagePath();
                                    img.Path    = item.Path;
                                    img.File    = bitmapImage;
                                    img.Storage = item;
                                    imgList.Add(img);
                                }

                                //imageView.ItemsSource = imgList;
                            }
                        }
                    }
                }
                catch (Exception exce)
                {
                    await new MessageDialog(exce.ToString()).ShowAsync();
                    throw exce;
                }
            }
        }
Example #16
0
        //update VOC CF
        private async void UpdateCF(string Name)
        {
            try
            {
                string methodFileName = methodtrans[Name];
                //Create a folder: fileFloder dir calibrate -->methodFileName -->dateTimeFileName
                StorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
                StorageFolder retentionFolder   = await applicationFolder.CreateFolderAsync("calibrate_test",
                                                                                            CreationCollisionOption.OpenIfExists);

                StorageFolder pdfFolder = await retentionFolder.CreateFolderAsync(methodFileName,
                                                                                  CreationCollisionOption.OpenIfExists);

                //Query the file
                List <string> fileTypeFilter = new List <string>();
                fileTypeFilter.Add(".dat");
                var queryOptions = new Windows.Storage.Search.QueryOptions(Windows.Storage.Search.CommonFileQuery.OrderByName, fileTypeFilter);

                // Create query and retrieve files
                var query = pdfFolder.CreateFileQueryWithOptions(queryOptions);
                IReadOnlyList <StorageFile> fileList = await query.GetFilesAsync();

                // Process results
                long maxvalue = 0;
                foreach (StorageFile file in fileList)
                {
                    // Process file
                    Debug.WriteLine(file.Name);
                    if (long.Parse(file.Name.Split('.')[0]) > maxvalue)
                    {
                        maxvalue = long.Parse(file.Name.Split('.')[0]);
                    }
                }
                Debug.WriteLine(maxvalue);

                //Get the latest file
                string      latestFilename = maxvalue.ToString() + ".dat";
                StorageFile latestFile     = await pdfFolder.GetFileAsync(latestFilename);

                if (latestFile != null)
                {
                    Debug.WriteLine("Update file found");
                }

                IBuffer buffer = await FileIO.ReadBufferAsync(latestFile);

                DataReader reader      = DataReader.FromBuffer(buffer);
                byte[]     fileContent = new byte[reader.UnconsumedBufferLength];
                reader.ReadBytes(fileContent);

                string text = GetEncoding(new byte[4] {
                    fileContent[0], fileContent[1], fileContent[2], fileContent[3]
                }).GetString(fileContent);
                String[] result = text.Split(new[] { '|' });
                if (result.Length == VOCLibraryList.Count)
                {
                    newinfo = new string[result.Length + 1, 2];
                    for (int i = 0; i < result.Length; i++)
                    {
                        for (int j = 0; j < 2; j++)
                        {
                            string[] newline = result[i].Split(new[] { ':' });
                            newinfo[i, j] = newline[j];
                        }
                    }
                    newinfo[result.Length, 0] = "datetime";
                    newinfo[result.Length, 1] = maxvalue.ToString();
                }
                if (newinfo.Length > 0)
                {
                    for (var index = 0; index < VOCLibraryList.Count; index++)
                    {
                        VOCLibraryList[index].CalibrateDate = newinfo[VOCLibraryList.Count, 1];
                        //info.ConcentrationFactor = json.GetNamedNumber("CalibrationFactor").ToString();
                        VOCLibraryList[index].ConcentrationFactor = newinfo[index, 1];
                        //if (!json.GetNamedArray("VOCRetentionTime")[0].ToString().Equals("null"))
                        //{
                        //    VOCLibraryList[index].Time = json.GetNamedArray("VOCRetentionTime")[index].GetNumber().ToString();
                        //}
                        //else
                        //{
                        //    VOCLibraryList[index].Time = "--";
                        //}
                    }
                }
            }
            catch (FileNotFoundException)
            {
                Debug.WriteLine("Update file not found");
            }
            //update CF
        }
Example #17
0
        //update retention
        private async void UpdateRentention(string name)
        {
            try
            {
                RetentionTimeList = new List <double>();
                string methodFileName = methodtrans[name];
                //Create a folder: fileFloder dir calibrate -->methodFileName -->dateTimeFileName
                StorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
                StorageFolder retentionFolder   = await applicationFolder.CreateFolderAsync("Retention_update",
                                                                                            CreationCollisionOption.OpenIfExists);

                StorageFolder pdfFolder = await retentionFolder.CreateFolderAsync(methodFileName,
                                                                                  CreationCollisionOption.OpenIfExists);

                //Query the file
                List <string> fileTypeFilter = new List <string>();
                fileTypeFilter.Add(".dat");
                var queryOptions = new Windows.Storage.Search.QueryOptions(Windows.Storage.Search.CommonFileQuery.OrderByName, fileTypeFilter);

                // Create query and retrieve files
                var query = pdfFolder.CreateFileQueryWithOptions(queryOptions);
                IReadOnlyList <StorageFile> fileList = await query.GetFilesAsync();

                // Process results
                long maxvalue = 0;
                foreach (StorageFile file in fileList)
                {
                    // Process file
                    Debug.WriteLine(file.Name);
                    if (long.Parse(file.Name.Split('.')[0]) > maxvalue)
                    {
                        maxvalue = long.Parse(file.Name.Split('.')[0]);
                    }
                }
                Debug.WriteLine(maxvalue);

                //Get the latest file
                string      latestFilename = maxvalue.ToString() + ".dat";
                StorageFile latestFile     = await pdfFolder.GetFileAsync(latestFilename);

                if (latestFile != null)
                {
                    Debug.WriteLine("Update file found");
                }

                IBuffer buffer = await FileIO.ReadBufferAsync(latestFile);

                DataReader reader      = DataReader.FromBuffer(buffer);
                byte[]     fileContent = new byte[reader.UnconsumedBufferLength];
                reader.ReadBytes(fileContent);
                string text = GetEncoding(new byte[4] {
                    fileContent[0], fileContent[1], fileContent[2], fileContent[3]
                }).GetString(fileContent);
                String[] result = text.Split(new[] { ',' });
                for (int i = 0; i < result.Length; i++)
                {
                    RetentionTimeList.Add(double.Parse(result[i]));
                    Debug.WriteLine(result[i]);
                }
                for (var index = 0; index < RetentionTimeList.Count; index++)
                {
                    VOCLibraryList[index].Time = RetentionTimeList[index].ToString("0.00");
                }
            }
            catch (FileNotFoundException)
            {
                Debug.WriteLine("Update file not found");
            }
        }
        /// <summary>
        /// This is the click handler for all four buttons in this example.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void Default_Click(object sender, RoutedEventArgs e)
        {
            Button b = sender as Button;
            if (b != null)
            {
                OutputProgressRing.IsActive = true;

                // Each visible button was previously set to display a homegroup user's name
                string userName = b.Content.ToString();

                // This try/catch block is for scenarios where the Homegroup Known Folder is not available.
                try
                {
                    System.Collections.Generic.IReadOnlyList<Windows.Storage.StorageFolder> hgFolders = await Windows.Storage.KnownFolders.HomeGroup.GetFoldersAsync();
                    bool userFound = false;

                    foreach (Windows.Storage.StorageFolder folder in hgFolders)
                    {
                        if (folder.DisplayName == userName)
                        {
                            // We've found the folder belonging to the target user; search for all files under it
                            userFound = true;
                            Windows.Storage.Search.QueryOptions queryOptions = new Windows.Storage.Search.QueryOptions(Windows.Storage.Search.CommonFileQuery.OrderBySearchRank, null);
                            queryOptions.UserSearchFilter = "*";
                            Windows.Storage.Search.StorageFileQueryResult queryResults = folder.CreateFileQueryWithOptions(queryOptions);
                            System.Collections.Generic.IReadOnlyList<Windows.Storage.StorageFile> files = await queryResults.GetFilesAsync();

                            if (files.Count > 0)
                            {
                                string outputString = (files.Count == 1) ? "One file found\n\n" : files.Count.ToString() + " files found\n\n";
                                foreach (Windows.Storage.StorageFile file in files)
                                {
                                    outputString += file.Name + "\n";
                                }
                                rootPage.NotifyUser(outputString, NotifyType.StatusMessage);
                            }
                            else
                            {
                                rootPage.NotifyUser("No files found.", NotifyType.StatusMessage);
                            }
                        }
                    }

                    if (!userFound)
                    {
                        rootPage.NotifyUser("The user " + userName + " was not found on the HomeGroup.", NotifyType.ErrorMessage);
                    }
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
                }
                OutputProgressRing.IsActive = false;
            }
        }
Example #19
0
        /// <summary>
        /// returns a list of filenames for the 
        /// specified directory.
        /// </summary>
        /// <param name="directoryPath"></param>
        /// <returns></returns>
        public async Task<List<string>> GetFileNames(string directoryPath, string pattern)
        {
            List<string> listFile = new List<string>();
            List<string> fileTypeFilter = new List<string>();
            fileTypeFilter.Add(pattern);

            Windows.Storage.Search.QueryOptions queryOptions = new Windows.Storage.Search.QueryOptions(Windows.Storage.Search.CommonFileQuery.OrderBySearchRank, fileTypeFilter);
            queryOptions.UserSearchFilter = directoryPath;
            var fileQuery = applicationData.LocalFolder.CreateFileQueryWithOptions(queryOptions);

            var list = await fileQuery.GetFilesAsync();
            if (list != null)
                foreach (var file in list)
                    listFile.Add(file.Path);
            return listFile;
        }
        /// <summary>
        /// 重载函数处理传入参数
        /// </summary>
        /// <param name="e">Folder类型,为即将显示的界面的根目录</param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            //SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = Frame.CanGoBack ?
            //        AppViewBackButtonVisibility.Visible : Windows.UI.Core.AppViewBackButtonVisibility.Collapsed;

            //base.OnNavigatedTo(e);
            MainStackPanel.Visibility  = Visibility.Collapsed;
            EmptyFolderText.Visibility = Visibility.Visible;

            viewModel = FolderViewModel.GetInstance();

            // 就是currentFolder = e.parameter as folder 然后判断一下不为null
            if (e.Parameter is Folder currentFolder)
            {
                currentRootFolder = currentFolder;
                try
                {
                    folders.Clear();
                    bool wheatherShowEmpty = true;
                    var  folder            = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFolderAsync(currentRootFolder.Token);

                    if (folder != null)
                    {
                        var foldersQuery = folder.CreateFolderQuery();

                        foreach (var eachfolder in await foldersQuery.GetFoldersAsync())
                        {
                            wheatherShowEmpty = false;
                            string token = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(eachfolder);
                            folders.Add(new Folder(token, eachfolder.Name, await GetNumInFolder(eachfolder)));
                        }

                        var filesQuery = new Windows.Storage.Search.QueryOptions();
                        filesQuery.FileTypeFilter.Add(".mp4");
                        filesQuery.FileTypeFilter.Add(".wma");
                        filesQuery.FileTypeFilter.Add(".avi");

                        var query = folder.CreateFileQueryWithOptions(filesQuery);
                        var files = await query.GetFilesAsync();

                        foreach (var file in files)
                        {
                            BitmapImage bitmapImage = await Common.GetThumbnailOfVideo(file);

                            wheatherShowEmpty = false;
                            Video temp = await viewModel.Search(file.Path);

                            string videoToken;
                            string date = DateTimeOffset.Now.Year.ToString() + "/" + DateTimeOffset.Now.Month.ToString() + "/" + DateTimeOffset.Now.Day.ToString();
                            if (temp == null)
                            {
                                videoToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file);
                                videos.Add(new Video(videoToken, file.Name, date, "", 0, 0, 0, 0, file.Path, bitmapImage));
                            }
                            else
                            {
                                temp.Date = date;
                                videos.Add(temp);
                            }
                        }
                    }
                    if (!wheatherShowEmpty)
                    {
                        MainStackPanel.Visibility  = Visibility.Visible;
                        EmptyFolderText.Visibility = Visibility.Collapsed;
                    }
                }
                catch (Exception)
                {
                    await new MessageDialog("Path is not valid").ShowAsync();
                }
            }
        }