/// <summary> /// Gets a new filename which starts as the base filename parameter, but has a different end part. /// </summary> /// <param name="folder">The folder where the name will be checked.</param> /// <param name="baseFileName">Base filename to use as root.</param> /// <returns> /// The new filename. /// </returns> /// <example> /// In case that "naruto" does not exist in folder. /// GetNewFileName(folder, "naruto") -> "naruto" /// GetNewFileName(folder, "naruto") -> "naruto_1" /// GetNewFileName(folder, "naruto") -> "naruto_2" /// ... /// </example> public static string GetNewFileName(StorageFolder folder, string baseFileName) { try { var names = folder.GetFilesAsync() .AsTask().Result .Select(f => Path.GetFileNameWithoutExtension(f.Name)); string possibleName = baseFileName; int index = 1; while (true) { if (names.Any(n => n.Equals(possibleName, StringComparison.CurrentCultureIgnoreCase))) { possibleName = baseFileName + index++; } else { break; } } return possibleName; } catch (Exception) { return baseFileName; } }
private async void Button_Click(object sender, RoutedEventArgs e) { var folderpicker = new Windows.Storage.Pickers.FolderPicker(); folderpicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.ComputerFolder; folderpicker.FileTypeFilter.Add("*"); Windows.Storage.StorageFolder folder = await folderpicker.PickSingleFolderAsync(); string pathstr = folder.Path; Windows.Storage.StorageFile file = await folder.CreateFileAsync("sample.txt", CreationCollisionOption.GenerateUniqueName); List <string> output = new List <string>(); foreach (StorageFile sfile in await folder.GetFilesAsync()) { output.Add(sfile.Name + "\n"); } stores.ItemsSource = output; if (!string.IsNullOrEmpty(path.Text) && !string.IsNullOrWhiteSpace(path.Text)) { //string Path = path.Text; //DataAccess.AddData(Path); //StoreDirectories.Stores = await DataAccess.GetStores(); //stores.ItemsSource = StoreDirectories.Stores; } }
/// <summary> /// Opens the file dialog, to select the images /// which will be shown. /// </summary> private async Task OpenFileDialogAsync() { this.IsLoading = true; var folderPicker = new Windows.Storage.Pickers.FolderPicker(); folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync(); this.Pictures.Clear(); try { IReadOnlyList<StorageFile> files = await folder.GetFilesAsync(); foreach (StorageFile filename in files) { this.Pictures.Add(await LoadPictureAsync(filename.Path)); } } catch (Exception) { } finally { this.IsLoading = false; } }
public async Task autoSaveMap() { try { String now = DateTime.Now.ToString("yyyyMMddHHmmssfff"); Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; if (localFolder != null) { IReadOnlyList <StorageFile> dirFiles = await localFolder.GetFilesAsync(); if (dirFiles != null) { if (dirFiles.Count > maxAutoSaves) { String filename = dirFiles.First().Name; StorageFile firstfile = await localFolder.GetFileAsync(filename); await firstfile.DeleteAsync(); } } String name = "Autosave" + now + ".ppm"; Windows.Storage.StorageFile file = await localFolder.CreateFileAsync(name); filemanager.WriteFile(path, file); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Autosave failed: Message:" + e.Message); } }
public async Task openAutoSave() { try { Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; IReadOnlyList <StorageFile> dirFiles = await localFolder.GetFilesAsync(); if (dirFiles != null) { if (dirFiles.Count > 0) { String name = dirFiles.Last().Name; StorageFile last = await localFolder.GetFileAsync(name); // Process input if the user clicked OK. if (last != null) { await filemanager.ReadFile(last.Path, last); GlobalNodeHandler.viewNode = GlobalNodeHandler.masterNode; GlobalNodeHandler.viewNode.UpdateViewRepresentation(); } } } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Could not open AutoSave: Message:" + e.Message); } }
private async void GetAllFiles(StorageFolder folder, ObservableCollection<Song> songs) { foreach (StorageFile file in await folder.GetFilesAsync()) { if(file.FileType == ".mp3") { var props = await file.Properties.GetMusicPropertiesAsync(); var image = await file.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.MusicView); var cover = new BitmapImage(); cover.SetSource(image); Song song = new Song() { Name = props.Title, Album = props.Album, Artist = props.Artist, Cover = cover, File = file }; songs.Add(song); } } foreach (StorageFolder subfolder in await folder.GetFoldersAsync()) { GetAllFiles(subfolder, songs); } }
private async void BtnOpenFolderDialogClick(object sender, RoutedEventArgs e) { var folderPicker = new Windows.Storage.Pickers.FolderPicker(); folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; folderPicker.FileTypeFilter.Add("*"); Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync(); if (folder != null) { // Application now has read/write access to all contents in the picked folder // (including other sub-folder contents) Windows.Storage.AccessCache.StorageApplicationPermissions. FutureAccessList.AddOrReplace("PickedFolderToken", folder); files = await folder.GetFilesAsync(); if (files.Count > 0) { filesNames.Clear(); // Application now has read/write access to the picked file(s) foreach (Windows.Storage.StorageFile file in files) { filesNames.Add(file.Name); } comboImagesNames.DataContext = filesNames; comboImagesNames.UpdateLayout(); comboImagesNames.SelectionChangedTrigger = ComboBoxSelectionChangedTrigger.Always; // comboImagesNames.SelectedItem = filesNames[0]; } } }
private async void OpenImageFolder(object sender, RoutedEventArgs e) { //imgpicker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; //imgpicker.FileTypeFilter.Add(".jpg"); //imgpicker.FileTypeFilter.Add(".jpeg"); //imgpicker.FileTypeFilter.Add(".png"); //imgpicker.FileTypeFilter.Add(".bmp"); //imgpicker.FileTypeFilter.Add(".gif"); //imagefile = await imgpicker.PickSingleFileAsync(); //if (imagefile == null) return; //Tot.Text = imagefile.ContentType.ToString(); //if (imagefile == null) return; //IRandomAccessStream inputstream = await imagefile.OpenReadAsync(); //ImageProperties imageProperties = await imagefile.Properties.GetImagePropertiesAsync(); //BitmapImage bitmap = new BitmapImage(); //bitmap.SetSource(inputstream); //ImagePlace.Source = bitmap; btnOpn.IsEnabled = false; imgfpik.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; imgfpik.FileTypeFilter.Add(".jpg"); imgfpik.FileTypeFilter.Add(".jpeg"); imgfpik.FileTypeFilter.Add(".png"); imgfpik.FileTypeFilter.Add(".bmp"); imagefolder = await imgfpik.PickSingleFolderAsync(); if (imagefolder == null) { btnOpn.IsEnabled = true; return; } imgfiles = await imagefolder.GetFilesAsync(); if (imgfiles.Count < 1) { btnOpn.IsEnabled = true; return; } int rankey = ran.Next(0, imgfiles.Count); imagefile = imgfiles.ElementAt <StorageFile>(rankey); if (imagefile == null) { return; } Tot.Text = imagefile.ContentType.ToString(); if (imagefile == null) { return; } inputstream = await imagefile.OpenReadAsync(); ImageProperties imageProperties = await imagefile.Properties.GetImagePropertiesAsync(); horbitmap.SetSource(inputstream); HorImagePlace.Source = horbitmap; btnSat.IsEnabled = true; VerImagePlace.Visibility = Visibility.Collapsed; }
private void GetNote() { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; files = storageFolder.GetFilesAsync().GetAwaiter().GetResult(); foreach (var file in files) { noteItems.Add(file.Name); } }
public async Task getFiles(List<StorageFile> list, StorageFolder parent) { foreach (var item in await parent.GetFilesAsync()) { list.Add(item); } foreach (var item in await parent.GetFoldersAsync()) await getFiles(list, item); }
private async void GetMusics(StorageFolder folder) { // Get all the songs in the folder past in parameter foreach (var item in await folder.GetFilesAsync()) { if (item.FileType == ".mp3") allSongs.Add(item); } }
public async Task getFiles(List<StorageFile> list, StorageFolder parent) { //get all files of type folder search use Recursion foreach (var item in await parent.GetFilesAsync()) { list.Add(item); } foreach (var item in await parent.GetFoldersAsync()) await getFiles(list, item); }
public async Task<int> SelectGameExecutables(StorageFolder folder) { IEnumerable<StorageFile> retrievedFiles = await folder.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByName); var fileCount = retrievedFiles.Count(); Files = retrievedFiles.Where(file => ValidateFile(file)).ToList(); return Files.Count; }
protected override async void OnNavigatedTo(NavigationEventArgs e) { printHelper.register(); save_ink("blank.gif"); // create a blank file to create new pages later Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; IReadOnlyList <StorageFile> files = Task.Run(async() => { return(await storageFolder.GetFilesAsync()); }).GetAwaiter().GetResult(); List <Task> tasks = new List <Task>(); int numPages = 0; foreach (var file in files) { // TODO should check that it starts with number and no missing pages (e.g. 0,1,3...) if (file.Name.EndsWith(page_file_name)) { int pageID = int.Parse(file.Name.Split('_')[0]); InkPage ip = new InkPage(pageID); // AsyncHelpers.RunSync(() => ip.loadAsync()); await ip.loadAsync(); pageBuffers.Add(pageID, ip); numPages++; } } if (pageBuffers.Count > 0) { // TODO not needed? last_page = numPages - 1; // load 0_Page.gif // load_ink(cur_page.ToString() + page_file_name); } // else last_page=0, which is the current blank page else { pageBuffers.Add(0, new InkPage(0)); } replaceCanvas(pageBuffers[0]); }
private async System.Threading.Tasks.Task GetListNoteAsync() { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; files = await storageFolder.GetFilesAsync(); foreach (var file in files) { Debug.WriteLine(file.Name); notes.Add(file.Name); } }
private async Task retrieveFilesInFolders(ObservableCollection<StorageFile> list,StorageFolder parent) { foreach (var item in await parent.GetFilesAsync()) { if (item.FileType == ".mp3") list.Add(item); } foreach (var item in await parent.GetFoldersAsync()) { await retrieveFilesInFolders(list, item); } }
internal async static Task MergeFolders(StorageFolder source, StorageFolder target) { foreach (StorageFile sourceFile in await source.GetFilesAsync()) { await sourceFile.CopyAndReplaceAsync(await target.CreateFileAsync(sourceFile.Name, CreationCollisionOption.OpenIfExists)); } foreach (StorageFolder sourceDirectory in await source.GetFoldersAsync()) { StorageFolder nextTargetSubDir = await target.CreateFolderAsync(sourceDirectory.Name, CreationCollisionOption.OpenIfExists); await MergeFolders(sourceDirectory, nextTargetSubDir); } }
private async void LoadImagesFromDirectory(StorageFolder imagesdirectory) { Images.Clear(); var files = await imagesdirectory.GetFilesAsync(); foreach (var file in files) { Images.Add(new PhotoDto { ID = Guid.NewGuid(), Image = await LoadImage(file) }); } }
/// <summary> /// Initializes this instance. /// Load the images of Mobile Vikings team. /// </summary> /// <returns></returns> public async Task<bool> Initialize() { try { var assets = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets"); _folder = await assets.GetFolderAsync("People"); _files = await _folder.GetFilesAsync(); } catch (Exception ex) { return false; } return true; }
/// <summary> /// Returns the number of files within the Oxford Whitelist /// </summary> public static async Task<int> GetFileCountInWhitelist(StorageFolder folder) { int fileCount = 0; fileCount += (await folder.GetFilesAsync()).Count; var subFolders = await folder.GetFoldersAsync(); foreach(var subFolder in subFolders) { fileCount += (await subFolder.GetFilesAsync()).Count; } return fileCount; }
// first - a method to retrieve files from folder recursively private static async Task RetriveFilesInFolder(List<StorageFile> list, StorageFolder parent) { list.AddRange((await parent.GetFilesAsync()).Where(p => p.FileType == ".wma" || p.FileType == ".flac" || p.FileType == ".m4a" || p.FileType == ".mp3")); //avoiding DRM folder of xbox music foreach (var folder in (await parent.GetFoldersAsync()).Where(folder => folder.Name != "Xbox Music" && folder.Name != "Subscription Cache" && folder.Name != "Podcasts")) { await RetriveFilesInFolder(list, folder); } }
public async void GetFile() { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; // Get the first 20 files in the current folder, sorted by date. IReadOnlyList <StorageFile> sortedItems = await storageFolder.GetFilesAsync(CommonFileQuery.OrderByDate, 0, 20); // Iterate over the results and print the list of files // to the Visual Studio Output window. foreach (StorageFile file in sortedItems) { Debug.WriteLine(file.Name + ", " + file.DateCreated); } }
async Task<List<string>> _getAllFilesInFolderRecurse(StorageFolder currentFolder, string topFolder) { List<string> files = new List<string>(); foreach (var f in await currentFolder.GetFoldersAsync()) { files.AddRange(await _getAllFilesInFolderRecurse(f, topFolder)); } var filesResult = await currentFolder.GetFilesAsync(); var filesString = filesResult.Select(_ => _.Path.Replace(topFolder, "").Trim('\\')).ToList(); files.AddRange(filesString); return files; }
async private System.Threading.Tasks.Task SetLocalDirMedia() { var folderPicker = new Windows.Storage.Pickers.FolderPicker { SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop }; folderPicker.FileTypeFilter.Add(".wmv"); folderPicker.FileTypeFilter.Add(".mp4"); folderPicker.FileTypeFilter.Add(".wma"); folderPicker.FileTypeFilter.Add(".mp3"); Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync(); if (folder != null) { Windows.Storage.AccessCache.StorageApplicationPermissions. FutureAccessList.AddOrReplace("PickedFolderToken", folder); speedText.Text = "Picked folder: " + folder.Name; IReadOnlyList <StorageFile> fileList = await folder.GetFilesAsync(); bool first = false; foreach (StorageFile file in fileList) { VideoFileInfoList.Add(new VideoFileInfoData(file.Name, file.Path)); // mediaPlayer is a MediaPlayerElement defined in XAML if (file != null) { if (!first) { mediaPlayer.Source = MediaSource.CreateFromStorageFile(file); mediaPlayer.MediaPlayer.Play(); first = true; } } } } else { UpShowText("Operation cancelled."); } }
public async void GetAllPictures(StorageFolder folder) { // Get all the Pictures in the folder past in parameter foreach (var item in await folder.GetFilesAsync()) { if (item.FileType == ".jpg" || item.FileType == ".jpeg" || item.FileType == ".tif" || item.FileType == ".tiff" || item.FileType == ".png" || item.FileType == ".gif" || item.FileType == ".bmp" || item.FileType == ".dib" || item.FileType == ".wdp") allPictures.Add(item); } // Pluck off meta data from pictures GetInformationPictures(allPictures); }
/// <summary> /// Return the list of files in the local folder /// </summary> /// <returns></returns> public static async Task <IReadOnlyList <IStorageFile> > Files() { Windows.Storage.StorageFolder LocalFolder = Windows.Storage.ApplicationData.Current.LocalFolder; try { IReadOnlyList <IStorageFile> Files = await LocalFolder.GetFilesAsync(); return(Files); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); return(null); } }
private async void OpenFileAsync() { Debug.Log("In Async "); var folderPicker = new Windows.Storage.Pickers.FolderPicker(); folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; folderPicker.FileTypeFilter.Add("*"); Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync(); if (folder != null) { // Application now has read/write access to all contents in the picked folder // (including other sub-folder contents) Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", folder); IReadOnlyList <StorageFile> sortedItems = await folder.GetFilesAsync(CommonFileQuery.OrderByName); utility.numFrames = sortedItems.Count - 1; frameCounter = sortedItems.Count - 1; List <StreamReader> stream_reader_files = new List <StreamReader>(); Debug.Log("total number of files: " + sortedItems.Count); foreach (StorageFile file in sortedItems) { var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); using (var inputStream = stream.GetInputStreamAt(0)) { var reader = new DataReader(inputStream); byteArray = new byte[stream.Size]; await reader.LoadAsync((uint)stream.Size); reader.ReadBytes(byteArray); stream_reader_files.Add(new StreamReader(new MemoryStream(byteArray))); } } Debug.Log("the stream_reader_files length is:" + stream_reader_files.Count); utility.ReadFrames(stream_reader_files); utility.GetStructureData(); isAsyncDone = true; Debug.Log("GetStructureData in async in working."); } else { Debug.Log("cancelled. clicked"); isCancelled = true; } }
/// <summary> /// Store the content to the local storage of this device /// </summary> /// <param name="Content"></param> /// <param name="Filename"></param> public static async Task DeleteAll() { try { Windows.Storage.StorageFolder LocalFolder = Windows.Storage.ApplicationData.Current.LocalFolder; IReadOnlyList <StorageFile> LocalFiles = await LocalFolder.GetFilesAsync(); foreach (StorageFile File in LocalFiles) { await File.DeleteAsync(); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); } }
private static async Task<Album> CreateAlbum(StorageFolder albumFolder) { var rgx = new Regex(@"(.*) \[([0-9]*)\] - (.*)"); var match = rgx.Match(albumFolder.Name); var songfiles = (await albumFolder.GetFilesAsync()).Where(f => f.FileType != ".jpg"); var coverfile = await albumFolder.GetFileAsync("Cover.jpg"); return new Album { Id = albumFolder.Path, Artist = match.Groups[1].Value, Year = int.Parse(match.Groups[2].Value), Name = match.Groups[3].Value, CoverArt = new Uri(coverfile.Path), Songs = await Task.WhenAll(songfiles.Select(CreateSong)) }; }
private async Task DeleteFolderRecursivelyAsync(StorageFolder folder) { IReadOnlyList<StorageFolder> folders = await folder.GetFoldersAsync(); if (folders.Count > 0) { foreach (StorageFolder subFolder in folders) { await DeleteFolderRecursivelyAsync(subFolder); } } IReadOnlyList<StorageFile> files = await folder.GetFilesAsync(); foreach (StorageFile file in files) { await file.DeleteAsync(StorageDeleteOption.PermanentDelete); } }
private async void readFolder() { try { _logFileFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync("ErrorLogs"); IReadOnlyList<StorageFile> logFileList = await _logFileFolder.GetFilesAsync(); files = logFileList.ToArray(); foreach (StorageFile currentFile in files.Reverse()) { logFileListView.Items.Add(currentFile); } } catch(Exception ex) { ErrorLogger.printErrorToLog(ex.StackTrace, ex.Message); } }
public static async Task<bool> AddDownload(string filename, string url, DownloadType type, StorageFolder folder = null) { try { var down = new BackgroundDownloader(); down.TransferGroup = BackgroundTransferGroup.CreateGroup("other"); if (folder == null) { folder = await KnownFolders.MusicLibrary.GetFolderAsync("kgdownload"); switch (type) { case DownloadType.song: folder = await folder.GetFolderAsync("song"); down.TransferGroup = BackgroundTransferGroup.CreateGroup("song"); break; case DownloadType.mv: folder = await folder.GetFolderAsync("mv"); down.TransferGroup = BackgroundTransferGroup.CreateGroup("mv"); break; case DownloadType.other: folder = await folder.GetFolderAsync("other"); down.TransferGroup = BackgroundTransferGroup.CreateGroup("other"); break; default: break; } } var files= (await folder.GetFilesAsync()).ToList(); foreach (var item in files) { await item.DeleteAsync(); } var file = await folder.CreateFileAsync(filename); down.FailureToastNotification = DownloadToast(filename, DownloadResult.Failure); down.SuccessToastNotification = DownloadToast(filename, DownloadResult.Success); var opera= down.CreateDownload(new Uri(url), file); opera.CostPolicy = BackgroundTransferCostPolicy.Always; opera.StartAsync(); return true; } catch (Exception) { return false; } }
async public static void copyFolder(StorageFolder from, StorageFolder _to) { StorageFolder to = await _to.CreateFolderAsync(from.Name, CreationCollisionOption.OpenIfExists); IReadOnlyList<StorageFile> storageFiles = await from.GetFilesAsync(); foreach (var storageFile in storageFiles) { await storageFile.CopyAsync(to, storageFile.Name, NameCollisionOption.ReplaceExisting); } //IReadOnlyList<StorageFolder> storageFolders = await from.GetFoldersAsync(); var queryResult = from.CreateFolderQuery(); IReadOnlyList<StorageFolder> storageFolders = await queryResult.GetFoldersAsync(); foreach (var storageFolder in storageFolders) { copyFolder(storageFolder, to); } }
public async static Task<MusicLibraryViewModel.AlbumItem> GetAlbumItemFromFolder(StorageFolder item, StorageFolderQueryResult albumQueryResult, int artistId) { var albumDataRepository = new AlbumDataRepository(); var musicAttr = await item.Properties.GetMusicPropertiesAsync(); var albumItem = await albumDataRepository.LoadAlbumViaName(artistId, musicAttr.Album); if (albumItem == null) { var thumbnail = await item.GetThumbnailAsync(ThumbnailMode.MusicView, 250); albumItem = new MusicLibraryViewModel.AlbumItem(thumbnail, musicAttr.Album, albumQueryResult.Folder.DisplayName) { ArtistId = artistId }; await albumDataRepository.Add(albumItem); } var files = await item.GetFilesAsync(CommonFileQuery.OrderByMusicProperties); await albumItem.LoadTracks(files); return albumItem; }
private async Task<AlbumViewModel> CreateAlbumViewModel(StorageFolder folder) { var files = await folder.GetFilesAsync(); if (files.Count == 0) return null; byte[] thumb = null; var thumbnail = await folder.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.PicturesView); if (thumbnail != null) { var stream = thumbnail.AsStreamForRead(); using (BinaryReader br = new BinaryReader(stream)) { thumb = br.ReadBytes((int)stream.Length); } } return new AlbumViewModel(App.AlbumService, folder.DisplayName, folder.Path, thumb); }
async void GetSongs() { Windows.Storage.StorageFolder fsongs = Windows.Storage.KnownFolders.MusicLibrary; Windows.Storage.StorageFolder fhorn = await fsongs.GetFolderAsync("Horn"); horn = MediaSource.CreateFromStorageFile(await fhorn.GetFileAsync("horn.mp3")); var songs = await fsongs.GetFilesAsync(); songscount = songs.Count; sources = new MediaSource[songscount]; int i = 0; foreach (var song in songs) { sources[i] = MediaSource.CreateFromStorageFile(song); await sources[i++].OpenAsync(); } }
public static async Task<string[]> GetFiles(StorageFolder dir) { string[] filenames = null; try { var files = await dir.GetFilesAsync(); IList<string> names = new List<string>(); foreach (StorageFile file in files) { string filename = file.Name; names.Add(filename); } filenames = names.ToArray(); } catch (Exception ex) { Debug.WriteLine(ex); } return filenames; }
internal async static Task<string> FindJSBundleInUpdateContents(StorageFolder updateFolder, string expectedFileName) { foreach (StorageFile file in await updateFolder.GetFilesAsync()) { string fileName = file.Name; if (fileName.Equals(expectedFileName)) { return fileName; } } foreach (StorageFolder folder in await updateFolder.GetFoldersAsync()) { string mainBundlePathInSubFolder = await FindJSBundleInUpdateContents(folder, expectedFileName); if (mainBundlePathInSubFolder != null) { return Path.Combine(folder.Name, mainBundlePathInSubFolder); } } return null; }
private async Task ZipFolderContents(StorageFolder sourceFolder, ZipArchive archive, string baseDirPath) { IReadOnlyList<StorageFile> files = await sourceFolder.GetFilesAsync(); Regex pattern = FileNamingParameters.GetRegex(); foreach (StorageFile file in files) { if (pattern.Match(file.Name).Success) { ZipArchiveEntry readmeEntry = archive.CreateEntry(file.Name); byte[] buffer = await ReadStorageFileToByteBuffer(file); Stream entryStream = readmeEntry.Open(); await entryStream.WriteAsync(buffer, 0, buffer.Length); await entryStream.FlushAsync(); entryStream.Dispose(); } } }
async private System.Threading.Tasks.Task getFolder() { var folderPicker = new Windows.Storage.Pickers.FolderPicker(); folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; folderPicker.FileTypeFilter.Add("*"); Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync(); if (folder != null) { StorageFile tempFile = null; // Application now has read/write access to all contents in the picked folder // (including other sub-folder contents) Windows.Storage.AccessCache.StorageApplicationPermissions. FutureAccessList.AddOrReplace("PickedFolderToken", folder); IReadOnlyList <StorageFile> sortedItems = await folder.GetFilesAsync(); foreach (Windows.Storage.StorageFile file in sortedItems) { if (isVideoType(file) || isAudioType(file)) { if (tempFile == null) { tempFile = file; } AddItemsToListView(file); } else { Debug.WriteLine(file.Name + "cant be added. Type: " + file.ContentType); } } mediaPlayer.Source = MediaSource.CreateFromStorageFile(tempFile); } }
private async Task <Experiment[]> LoadExperiments() { List <Experiment> output = new List <Experiment>(); Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; var files = await storageFolder.GetFilesAsync(); foreach (StorageFile f in files) { string xml = await Windows.Storage.FileIO.ReadTextAsync(f); try { output.Add((Experiment)Serialize.Xml_Deserialize_Object <Experiment>(xml)); } catch (Exception e) { Debug.WriteLine(e.Message); } } return(output.ToArray()); }
public async void ButtonBase_OnClick(object sender, RoutedEventArgs e) { var note = new Note { name = DateTime.Now.ToString("yyyy-MM-dd-hh-mm"), text = textNote.Text, }; Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = storageFolder.CreateFileAsync(note.name + ".txt", Windows.Storage.CreationCollisionOption.ReplaceExisting).GetAwaiter().GetResult(); Windows.Storage.FileIO.WriteTextAsync(sampleFile, note.text).GetAwaiter().GetResult(); Debug.WriteLine(sampleFile.Name); IReadOnlyList <StorageFile> listNotes = await storageFolder.GetFilesAsync(); foreach (StorageFile file in listNotes) { Debug.WriteLine(file.Name); } }
public async Task ListFilesInFolder(StorageFolder folder) { var foldersInFolder = await folder.GetFoldersAsync(); foreach (StorageFolder currentChildFolder in foldersInFolder) { await ListFilesInFolder(currentChildFolder); } var filesInFolder = await folder.GetFilesAsync(); foreach (StorageFile currentFile in filesInFolder) { if (currentFile.ContentType.IsImageFormat()) { var picture = new Picture(currentFile.Name, currentFile.DateCreated.DateTime, currentFile.Path); if (!pictures.Contains(picture)) { pictures.Add(picture); await picture.LoadImageAsync(); } } } }
public async Task IndexDataFolder(StorageFolder folder, int vertexLimit) { var files = await folder.GetFilesAsync(); foreach (var file in files) { var fileName = file.Name; var fileParts = fileName.Split(new char[] { '-' }); var idents = fileParts[0].Split(new char[] { '_' }); var eventId = idents[0]; if (_subjectsByEventId.ContainsKey(eventId)) { var subject = _subjectsByEventId[eventId]; if (!_adjBySubjectId.ContainsKey(subject.SubjectId)) _adjBySubjectId[subject.SubjectId] = new List<AdjFile>(); StringBuilder sbAdjType = new StringBuilder(); for (int i = 1; i < idents.Length; i++) { if (i > 1) sbAdjType.Append("-"); sbAdjType.Append(idents[i]); } AdjFile adj = new AdjFile(); adj.File = file; adj.Graph = new GraphViewModel(vertexLimit); adj.DataType = sbAdjType.ToString(); _adjBySubjectId[subject.SubjectId].Add(adj); } } }
private async void Initialize() { try { // Loop through the files in the samples-data shapefile folder and add them to the combobox. _folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("shapefiles"); var files = await _folder.GetFilesAsync(); foreach (var shpfile in files) { if (shpfile.FileType == ".shp") { FileListCombo.Items.Add(shpfile); FileListCombo.Visibility = (files.Any()) ? Visibility.Visible : Visibility.Collapsed; } } } catch (Exception ex) { var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync(); } }
/// <summary> /// ZipFolder and its sub folders /// </summary> /// <param name="tcpSocket"></param> async private static Task ZipFolderContents(StorageFolder sourceFolder, ZipArchive archive, string baseDirPath) { IReadOnlyList<StorageFile> files = await sourceFolder.GetFilesAsync(); foreach (StorageFile file in files) { ZipArchiveEntry readmeEntry = archive.CreateEntry(GetCompressedFileName(baseDirPath, file)); byte[] buffer = WindowsRuntimeBufferExtensions.ToArray(await FileIO.ReadBufferAsync(file)); // And write the contents to it using (Stream entryStream = readmeEntry.Open()) { await entryStream.WriteAsync(buffer, 0, buffer.Length); } } IReadOnlyList<StorageFolder> subFolders = await sourceFolder.GetFoldersAsync(); if (subFolders.Count() == 0) return; foreach (StorageFolder subfolder in subFolders) await ZipFolderContents(subfolder, archive, baseDirPath); }
async private void ListView_ItemClick(object sender, ItemClickEventArgs e) { speechAI.Text = e.ClickedItem.ToString(); if (speechAI.Text.Contains("폴더 선택")) { var folderPicker = new Windows.Storage.Pickers.FolderPicker(); folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; folderPicker.FileTypeFilter.Add("*"); _folder = await folderPicker.PickSingleFolderAsync(); if (_folder != null) { // Application now has read/write access to all contents in the picked folder // (including other sub-folder contents) Windows.Storage.AccessCache.StorageApplicationPermissions. FutureAccessList.AddOrReplace("PickedFolderToken", _folder); speechAI.Text = "Picked folder: " + _folder.Path; _fileList = await _folder.GetFilesAsync(); FolderFileList.Items.Clear(); if (_fileList.Count % 2 != 0) { speechAI.Text = "폴더 내의 파일이 짝수가 아닙니다."; return; } string 현재표시할라인; _oldlist.Clear(); _newlist.Clear(); for (int i = 0; i < _fileList.Count; i++) { 현재표시할라인 = _fileList[i].Name + " > RN" + string.Format("{0:0000}", Convert_HP_ScanedName(i, _fileList.Count)) + ".jpg"; FolderFileList.Items.Add(현재표시할라인); _oldlist.Add(_fileList[i].Path); _newlist.Add("RN" + string.Format("{0:0000}", Convert_HP_ScanedName(i, _fileList.Count)) + ".jpg"); } } else { speechAI.Text = "Operation cancelled."; } } else if (speechAI.Text.Contains("이름 바꾸기")) { //Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", _folder); for (int i = 0; i < _oldlist.Count; i++) { await _fileList[i].CopyAsync(_folder, _newlist[i], NameCollisionOption.ReplaceExisting); } } }
public async Task PrintFolderAsync(StorageFolder folder) { if (folder != null) { count++; Debug.WriteLine(this.getCount() + "folder : " + PtcEncoder.Decode(folder.Name) + "(" + folder.Path + ")"); IReadOnlyList<StorageFile> fileList = await folder.GetFilesAsync(); IReadOnlyList<StorageFolder> folderList = await folder.GetFoldersAsync(); foreach (StorageFile file in fileList) { PrintFile(file); } foreach (StorageFolder _folder in folderList) { await PrintFolderAsync(_folder); } count--; } }
private async void Button_Click(object sender, RoutedEventArgs e) { Tot.Text = ""; Vot.Text = ""; Button button = sender as Button; button.IsEnabled = false; StorageFolder vere = imagefolder; StorageFolder hore = imagefolder; if (imgfiles == null) { return; } //Tot.Text = imagefile.Path; Tot.Text = imagefile.FileType; //若存在则获取,不存在则新建 if (null == await imagefolder.TryGetItemAsync("Hor")) { hore = await imagefolder.CreateFolderAsync("Hor"); } hore = await imagefolder.GetFolderAsync("Hor"); if (await imagefolder.TryGetItemAsync("Ver") == null) { vere = await imagefolder.CreateFolderAsync("Ver"); } vere = await imagefolder.GetFolderAsync("Ver"); int a = 0; int b = 0; float t = 0; float p = 0; double c = 0; Tot.Text = a.ToString(); Vot.Text = b.ToString(); //Windows.Storage.StorageFolder imgfld = await imagefile.GetParentAsync(); StorageApplicationPermissions.FutureAccessList.Add(imagefolder); IReadOnlyList <StorageFile> filelist = await imagefolder.GetFilesAsync(); foreach (StorageFile file in filelist) { progrb.Visibility = Visibility.Visible; p = filelist.Count; if (file.FileType == ".jpg" || file.FileType == ".png" || file.FileType == ".bmp") { var varfil = await file.GetBasicPropertiesAsync(); if (varfil.Size == 0) { continue; } filename = file.Name; filename = varfil.Size.ToString(); errtag.Text = filename; ImageProperties imageProperties = await file.Properties.GetImagePropertiesAsync(); if (imageProperties.Width >= imageProperties.Height) { if (await hore.TryGetItemAsync(file.Name) != null) { continue; } inputstream = await file.OpenReadAsync(); await horbitmap.SetSourceAsync(inputstream); HorImagePlace.Source = horbitmap; await file.CopyAsync(hore); a++; } else { if (await vere.TryGetItemAsync(file.Name) != null) { continue; } inputstream = await file.OpenReadAsync(); await verbitmap.SetSourceAsync(inputstream); VerImagePlace.Visibility = Visibility.Visible; VerImagePlace.Source = verbitmap; await file.CopyAsync(vere); b++; } Tot.Text = a.ToString(); Vot.Text = b.ToString(); } Tot.Text += " Hor Pictures Copyed"; Vot.Text += " Ver Pictures Copyed"; button.IsEnabled = true; btnOpn.IsEnabled = true; t++; c = t / p; progrb.Value = c * 100; } StorageApplicationPermissions.FutureAccessList.Clear(); }
public async System.Threading.Tasks.Task<uint> BrowseFolder(StorageFolder folder) { // LogMessage("Discover folder Name: " + folder.Name + " Path: " + folder.Path + " files: [" + fileDiscovered + "] folders: [" + folderDiscovered + "]"); folderDiscovered++; if (ProgressEvent != null) ProgressEvent(folderDiscovered); await System.Threading.Tasks.Task.Delay(100); try { if (discoverCancelToken != null) if (discoverCancelToken.Token.IsCancellationRequested) discoverCancelToken.Token.ThrowIfCancellationRequested(); IReadOnlyList<StorageFolder> folders = await folder.GetFoldersAsync(CommonFolderQuery.DefaultQuery); foreach (var f in folders) { if (discoverCancelToken != null) if (discoverCancelToken.Token.IsCancellationRequested) discoverCancelToken.Token.ThrowIfCancellationRequested(); uint value = await BrowseFolder(f); } } catch (Exception e) { LogMessage("Discover folder exception: " + folder.Path + " Exception:" + e.Message); } uint currentFilesDiscovered = fileDiscovered; try { if (discoverCancelToken != null) if (discoverCancelToken.Token.IsCancellationRequested) discoverCancelToken.Token.ThrowIfCancellationRequested(); // IReadOnlyList<StorageFile> files = await folder.GetFilesAsync(CommonFileQuery.OrderByName); IReadOnlyList<StorageFile> files = await folder.GetFilesAsync(CommonFileQuery.DefaultQuery); foreach (var f in files) { if (discoverCancelToken != null) if (discoverCancelToken.Token.IsCancellationRequested) discoverCancelToken.Token.ThrowIfCancellationRequested(); string path = await GetPath(f); string extension = f.FileType; foreach (string e in extensionArray) { if (extension.EndsWith(e, StringComparison.CurrentCultureIgnoreCase)) { if (!defaultMediaDictionary.ContainsKey(path)) { MediaLibraryItem mli = new MediaLibraryItem(path); defaultMediaDictionary.Add(path, mli); fileDiscovered = (uint)defaultMediaDictionary.Count; } UpdateUI(); //statusValue.Text = fileDiscovered.ToString() + " files discovered"; // LogMessage("Discover file name: " + f.Name + " path: " + path); break; } } } } catch (Exception e) { LogMessage("Discover files exception: " + folder.Path + " Exception:" + e.Message); } if (currentFilesDiscovered != fileDiscovered) { UpdateCounter(); } return fileDiscovered; }
private async void Durchsuchen_Click(object sender, RoutedEventArgs _1) { int BootsIDCounter = 1; int Filecounter = 1; var folderPicker = new Windows.Storage.Pickers.FolderPicker { SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop }; folderPicker.FileTypeFilter.Add("*"); Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync(); if (folder != null) { DataAccess.Reset(); // Application now has read/write access to all contents in the picked folder // (including other sub-folder contents) Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", folder); DisplayImportwurdegestartet(); IReadOnlyList <StorageFile> filelist = await folder.GetFilesAsync(); FileImport_Progress_indicator.Maximum = filelist.Count; FileImport_Progress_indicator.Visibility = Visibility.Visible; foreach (StorageFile file in filelist) { if (file.FileType == ".xls" || file.FileType == ".xlsx") { FileImport_success_indicator.Text += "Successfully processed " + file.DisplayName + " at " + file.Path + " (" + file.FileType + ")\n"; //Get Exel ready ISheet sheet; using (Stream filetmp = await file.OpenStreamForReadAsync()) { if (file.FileType == ".xls") { HSSFWorkbook hssfwb; hssfwb = new HSSFWorkbook(filetmp); sheet = hssfwb.GetSheetAt(0); } else { XSSFWorkbook xssfwb; xssfwb = new XSSFWorkbook(filetmp); sheet = xssfwb.GetSheetAt(0); } } //import Exel to DataAcccess int BootsID = BootsIDCounter++; string RennID = CellLookup(sheet, "A12"); string Bootsname = CellLookup(sheet, "C26"); string Verein = CellLookup(sheet, "G12"); string Steuerling = NamenLookup(sheet, "D24", "C24"); string SteuerlingVerein = CellLookup(sheet, "G16"); string Athlet1 = NamenLookup(sheet, "D16", "C16"); string Athlet1Verein = CellLookup(sheet, "G16"); string Athlet2 = NamenLookup(sheet, "D17", "C17"); string Athlet2Verein = CellLookup(sheet, "G17"); string Athlet3 = NamenLookup(sheet, "D18", "C18"); string Athlet3Verein = CellLookup(sheet, "G18"); string Athlet4 = NamenLookup(sheet, "D19", "C19"); string Athlet4Verein = CellLookup(sheet, "G19"); string Athlet5 = NamenLookup(sheet, "D20", "C20"); string Athlet5Verein = CellLookup(sheet, "G20"); string Athlet6 = NamenLookup(sheet, "D21", "C21"); string Athlet6Verein = CellLookup(sheet, "G21"); string Athlet7 = NamenLookup(sheet, "D22", "C22"); string Athlet7Verein = CellLookup(sheet, "G22"); string Athlet8 = NamenLookup(sheet, "D23", "C23"); string Athlet8Verein = CellLookup(sheet, "G23"); string Meldername = NamenLookup(sheet, "G3", "D3"); string Melderadresse = FirstCharToUpper(CellLookup(sheet, "D4")); string Melderort = CellLookup(sheet, "D5") + " " + FirstCharToUpper(CellLookup(sheet, "F5")); string Melderverein = CellLookup(sheet, "D6"); string Melderemail = CellLookup(sheet, "D7").ToLower(); string Meldertel = CellLookup(sheet, "D8"); string Melderfax = CellLookup(sheet, "D9"); string Kommentare = CellLookup(sheet, "D27"); decimal Bezahlt = 0; DataAccess.AddData(BootsID, 0, 0, RennID, Bootsname, Verein, Steuerling, SteuerlingVerein, Athlet1, Athlet1Verein, Athlet2, Athlet2Verein, Athlet3, Athlet3Verein, Athlet4, Athlet4Verein, Athlet5, Athlet5Verein, Athlet6, Athlet6Verein, Athlet7, Athlet7Verein, Athlet8, Athlet8Verein, Meldername, Melderadresse, Melderort, Melderverein, Melderemail, Meldertel, Melderfax, Bezahlt, Kommentare); } else { FileImport_success_indicator.Text += "\nFataly failed to process " + file.DisplayName + " at " + file.Path + " (" + file.FileType + ")\n\n"; } FileImport_Progress_indicator.Value = Filecounter++; } durchsuchen.Background = new SolidColorBrush(Colors.Green); } else { FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender); } }