private static async Task InitDefaultDownloadFolder() { var futureAccessList = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList; if (!(await DefaultDownloadFolderExists())) { bool created = false; int i = 1; do { try { var myfolder = await DownloadsFolder.CreateFolderAsync((i == 1)? "Received" : $"Received ({i})"); FutureAccessListHelper.MakeSureFutureAccessListIsNotFull(); futureAccessList.AddOrReplace(_downloadMainFolder, myfolder); created = true; } catch { i++; } }while (!created); } }
public static async Task LoadFromJSONAsync() { StorageFolder storageFolder = ApplicationData.Current.LocalFolder; try { StorageFile ConfigFile = await storageFolder.GetFileAsync(App.configfilename); string configtext = await FileIO.ReadTextAsync(ConfigFile); ConfigData localdata = JsonConvert.DeserializeObject <ConfigData>(configtext); if (localdata != null) { if (localdata.HistoricalSearch != null) { App.historysearch = localdata.HistoricalSearch; } App.MyDownLoadFolder = localdata.MyDownLoadFolder; App.AutoPlay = localdata.AutoPlay; App.DeleteCache = localdata.DeleteCache; App.AutoSaveSearch = localdata.AutoSaveSearch; } } catch (Exception) // first open in user's compute { // create configdata.json await storageFolder.CreateFileAsync(App.configfilename); // init download folder, add folder in FutureAccessList with token (App.MyDownLoadFolder) StorageFolder newFolder = await DownloadsFolder.CreateFolderAsync("Music", CreationCollisionOption.GenerateUniqueName); StorageApplicationPermissions.FutureAccessList.AddOrReplace(App.MyDownLoadFolder, newFolder); } }
private async void Selection_Click_1(object sender, RoutedEventArgs e) { copy1.Text = "Copying...."; StorageFolder storeFolder = null; try { storeFolder = await DownloadsFolder.CreateFolderAsync(storfolder.Name.ToString(), CreationCollisionOption.GenerateUniqueName); if (ItemGridView.SelectedItems.Count != 0) { foreach (Item item in ItemGridView.SelectedItems) { //Uri uri = new Uri("ms-appdata:///local/" + item.Link); String[] filepath = parseString(item.Link); StorageFolder imageFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFolderAsync(filepath[0].Replace("/", "\\")); StorageFile storageFile = await imageFolder.GetFileAsync(filepath[1]); //StorageFile file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri); await storageFile.CopyAsync(storeFolder, item.Title, NameCollisionOption.GenerateUniqueName); } } } catch { DisplayMsg("Error copying selected files to Downloads!!!"); } ItemGridView.SelectedItems.Clear(); copy1.Text = "Copied to Downloads/ZipX/" + storeFolder.DisplayName; }
private async void CreateFolder_Tapped(object sender, TappedRoutedEventArgs e) { var futureAccessList = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList; var myfolder = await DownloadsFolder.CreateFolderAsync("QuickShare"); futureAccessList.Clear(); futureAccessList.AddOrReplace("downloadMainFolder", myfolder); }
private async void LoadSettings() { if (!settings.Values.ContainsKey(SavePathKey)) { var downloadFolder = await DownloadsFolder.CreateFolderAsync("SharedFiles", CreationCollisionOption.GenerateUniqueName); settings.Values.Add(SavePathKey, downloadFolder.Path); } SavePathField.Text = settings.Values[SavePathKey].ToString(); }
} // Download private async Task DownLoadFromAs(string inputURL, string filename, string albumcover = "") { StorageFolder MyDownloadFolder; // 定位 folder try { MyDownloadFolder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(App.MyDownLoadFolder); } catch (Exception) { MyDownloadFolder = await DownloadsFolder.CreateFolderAsync("Music", CreationCollisionOption.GenerateUniqueName); StorageApplicationPermissions.FutureAccessList.AddOrReplace(App.MyDownLoadFolder, MyDownloadFolder); } // check if exists music file try { StorageFile destinationFile = await MyDownloadFolder.CreateFileAsync(filename, CreationCollisionOption.FailIfExists); if (destinationFile != null) { if (PlayArea.Height >= DefaultHeight) { TextBlockStatus.Text = "0%"; DownloadBar.Value = 0; await DownloadBoard.Fade(value : 1.0f, duration : 500, delay : 0, easingType : EasingType.Default).StartAsync(); } Uri source = new Uri(inputURL); BackgroundDownloader downloader = new BackgroundDownloader(); DownloadOperation download = downloader.CreateDownload(source, destinationFile); Progress <DownloadOperation> progress = new Progress <DownloadOperation>(x => ProgressChanged(download)); cancellationToken = new CancellationTokenSource(); await download.StartAsync().AsTask(cancellationToken.Token, progress); if (DownloadBoard.Opacity == 1.0) { await DownloadBoard.Fade(value : 0.0f, duration : 1000, delay : 1000, easingType : EasingType.Default).StartAsync(); } } } catch (Exception) { // music exist FlyoutBase.ShowAttachedFlyout(DownLoadButton); } }
public async void CreateSurveyFolder(object sender, RoutedEventArgs e) { App.surveyFolder = await DownloadsFolder.CreateFolderAsync(SurveyNameInput.Text, CreationCollisionOption.FailIfExists); //ApplicationData.Current.LocalFolder.CreateFolderAsync(SurveyNameInput.Text, CreationCollisionOption.FailIfExists); App.surveyFile = await App.surveyFolder.CreateFileAsync(SurveyNameInput.Text + ".json", CreationCollisionOption.ReplaceExisting); App.assetsFolder = await App.surveyFolder.CreateFolderAsync("Assets", CreationCollisionOption.FailIfExists); /*folderPicker.FileTypeFilter.Add("*"); * folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; * App.surveyFolder = await folderPicker.PickSingleFolderAsync();*/ if (App.surveyFolder != null) { CurrentPageFrame.Navigate(typeof(SurveyPages.TitlePage)); } }
private async void DownloadMediaContent() { var dt = DateTime.Now; var f = await DownloadsFolder.CreateFolderAsync((dt.Year.ToString() + "-" + dt.Month.ToString() + "-" + dt.Day.ToString() + "-" + dt.Hour + "-" + dt.Minute), CreationCollisionOption.GenerateUniqueName); List <StorageFile> Files = new List <StorageFile>(); switch (_med.MediaType) { case InstaMediaType.Image: Files.Add(await f.CreateFileAsync("Img.jpg", CreationCollisionOption.GenerateUniqueName)); var file = Files.FirstOrDefault(); var tsk = new Windows.Networking.BackgroundTransfer.BackgroundDownloader().CreateDownload(new Uri(_med.Images[0].URI, UriKind.RelativeOrAbsolute), file).StartAsync().AsTask(); NotifyHelper.CreateNotifyEmpty("Download successfull", $"Image saved into {file.Path}"); break; case InstaMediaType.Video: Files.Add(await f.CreateFileAsync("Video.mp4", CreationCollisionOption.GenerateUniqueName)); var file2 = Files.FirstOrDefault(); var tsk2 = new Windows.Networking.BackgroundTransfer.BackgroundDownloader().CreateDownload(new Uri(_med.Videos[0].Url, UriKind.RelativeOrAbsolute), file2).StartAsync().AsTask(); NotifyHelper.CreateNotifyEmpty("Download successfull", $"Image saved into {file2.Path}"); break; case InstaMediaType.Carousel: foreach (var item in _med.Carousel) { if (item.MediaType == InstaMediaType.Image) { var file3 = await f.CreateFileAsync("Img.jpg", CreationCollisionOption.GenerateUniqueName); var tsk3 = new Windows.Networking.BackgroundTransfer.BackgroundDownloader().CreateDownload(new Uri(item.Images[0].URI, UriKind.RelativeOrAbsolute), file3).StartAsync().AsTask(); NotifyHelper.CreateNotifyEmpty("Download successfull", $"Image saved into {file3.Path}"); } else { var file3 = await f.CreateFileAsync("Video.mp4", CreationCollisionOption.GenerateUniqueName); var tsk3 = new Windows.Networking.BackgroundTransfer.BackgroundDownloader().CreateDownload(new Uri(item.Videos[0].Url, UriKind.RelativeOrAbsolute), file3).StartAsync().AsTask(); NotifyHelper.CreateNotifyEmpty("Download successfull", $"Video saved into {file3.Path}"); } } break; default: break; } }
public static async Task <IStorageFolder> GetOrCreateDownloadFolderAsync() { try { return(await StorageApplicationPermissions.MostRecentlyUsedList.GetFolderAsync( SettingEntries.DownloadsFolderToken)); } catch (Exception) { var folder = await DownloadsFolder.CreateFolderAsync( "Thunder X Downloaded", CreationCollisionOption.GenerateUniqueName); SettingEntries.DownloadsFolderToken = StorageApplicationPermissions.MostRecentlyUsedList.Add(folder); return(folder); } }
public async Task CreateTemporaryDirectory() { if (!Directory.Exists(this.OutputDirectory)) { try { StorageFolder newfolder = await DownloadsFolder.CreateFolderAsync(this.OutputDirectory, CreationCollisionOption.GenerateUniqueName); this.folder = newfolder; } catch (Exception e) when(e is UnauthorizedAccessException || e is PathTooLongException || e is DirectoryNotFoundException) { Console.WriteLine(e.Message); throw; } } }
async void PrepareSourse() { while (MusicRes == "shit") { } //not get resourse StorageFolder MyDownloadFolder; // 定位 folder try { MyDownloadFolder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(App.MyDownLoadFolder); } catch (Exception) { MyDownloadFolder = await DownloadsFolder.CreateFolderAsync("Music", CreationCollisionOption.GenerateUniqueName); StorageApplicationPermissions.FutureAccessList.AddOrReplace(App.MyDownLoadFolder, MyDownloadFolder); } // try to open exist file try { StorageFile music = await MyDownloadFolder.GetFileAsync(SongPLayingName.Text + MusicRes.Substring(0, 4)); var mediaSource = MediaSource.CreateFromStorageFile(music); App.Musicplayer.Source = mediaSource; mediaSource.OpenOperationCompleted += MediaSource_OpenOperationCompleted; } // not exist, download it catch (Exception) { StorageFile destinationFile = await MyDownloadFolder.CreateFileAsync(SongPLayingName.Text + MusicRes.Substring(0, 4), CreationCollisionOption.FailIfExists); var downloader = new BackgroundDownloader(); var downloadOperation = downloader.CreateDownload(new Uri(MusicRes.Substring(4)), destinationFile); await downloadOperation.StartAsync().AsTask(); var mediaSource = MediaSource.CreateFromStorageFile(destinationFile); App.Musicplayer.Source = mediaSource; mediaSource.OpenOperationCompleted += MediaSource_OpenOperationCompleted; } }
public async Task <bool> CreateFile(string directoryName, byte[] contentToWrite) { List <string> fileNames = directoryName.Split('/').ToList(); string downloadType = fileNames[1]; string comicName = fileNames[2]; string comicChapter = fileNames[3]; string comicFileName = fileNames[4]; StorageFile destinationFile; StorageFolder downloadsFolder; try { downloadsFolder = await DownloadsFolder.CreateFolderAsync(downloadType + @"\" + comicName + @"\" + comicChapter + @"\"); string folderToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(downloadsFolder); ApplicationData.Current.LocalSettings.Values["folderToken"] = folderToken; destinationFile = await downloadsFolder.CreateFileAsync(comicFileName, CreationCollisionOption.ReplaceExisting); await Windows.Storage.FileIO.WriteBytesAsync(destinationFile, contentToWrite); return(true); // File.WriteAllBytes(destinationFile.Path, contentToWrite); } catch (Exception ex) { if (ApplicationData.Current.LocalSettings.Values["folderToken"] != null) { string token = ApplicationData.Current.LocalSettings.Values["folderToken"].ToString(); downloadsFolder = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFolderAsync(token); destinationFile = await downloadsFolder.CreateFileAsync(comicFileName, CreationCollisionOption.ReplaceExisting); //File.WriteAllBytes(destinationFile.Path, contentToWrite); await Windows.Storage.FileIO.WriteBytesAsync(destinationFile, contentToWrite); return(true); } return(false); } }
private async void FirstRunWork() { if (Settings.DownloadFolderPath == null) { //第一次运行 try { var folder = await DownloadsFolder.CreateFolderAsync("DownloadsFolder", CreationCollisionOption.GenerateUniqueName); StorageApplicationPermissions.FutureAccessList.Clear(); StorageApplicationPermissions.FutureAccessList.Add(folder); Settings.DownloadFolderPath = folder.Path; } catch (Exception) { Settings.DownloadFolderPath = ApplicationData.Current.LocalCacheFolder.Path; } //打开帮助页面 await Launcher.LaunchUriAsync(new Uri(Settings.HelpLink)); } }
public async ValueTask <StorageFolder> GetVideoCacheFolder() { if (_DownloadFolder is not null) { return(_DownloadFolder); } StorageFolder folder = null; try { folder = await GetUserChoiceVideoFolder(); } catch (FileNotFoundException) { } if (folder is null) { return(await DownloadsFolder.CreateFolderAsync(FolderAccessToken, CreationCollisionOption.OpenIfExists)); } return(_DownloadFolder = folder); }
public async Task InitializeAsync() { if (_isInitialized) { return; } try { // キャッシュフォルダの指定 if (StorageApplicationPermissions.FutureAccessList.ContainsItem(CACHE_FOLDER_NAME)) { _videoCacheManager.VideoCacheFolder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(CACHE_FOLDER_NAME); } else { var folder = await DownloadsFolder.CreateFolderAsync(CACHE_FOLDER_NAME, CreationCollisionOption.GenerateUniqueName); StorageApplicationPermissions.FutureAccessList.AddOrReplace(CACHE_FOLDER_NAME, folder); _videoCacheManager.VideoCacheFolder = folder; } // キャッシュの暗号化を初期化 var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/VideoCache_EncryptionKey_32byte.txt")); var bytes = await file.ReadBytesAsync(); _videoCacheManager.SetXts(XTSSharp.XtsAes128.Create(bytes.Take(32).ToArray())); } catch (Exception e) { _logger.ZLogError(e, e.Message); } _isInitialized = true; }
private async void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) { this.gdRoot.Width = this.gdRoot.ActualWidth; var def = args.GetDeferral(); this.PrimaryButtonText = ""; this.SecondaryButtonText = ""; this.CloseButtonText = ""; FindName(nameof(this.rpDownload)); var folder = await DownloadsFolder.CreateFolderAsync(StorageHelper.ToValidFileName(this.release.tag_name), CreationCollisionOption.GenerateUniqueName); try { var arch = Package.Current.Id.Architecture.ToString(); if (this.release.assets.IsNullOrEmpty()) { throw new InvalidOperationException("Find appx file failed."); } var assets = (from asset in this.release.assets where asset.name.IndexOf(arch, StringComparison.OrdinalIgnoreCase) > 0 && downloadExt.Any(e => asset.name.EndsWith(e)) select asset).ToList(); if (assets.IsEmpty()) { throw new InvalidOperationException("Find appx file failed."); } var files = new List <StorageFile>(); var fileLaunched = false; using (var client = new HttpClient()) { try { this.totalDownloaded = assets.Sum(a => (long)a.size); foreach (var item in assets) { var op = client.GetBufferAsync(new Uri(item.browser_download_url)); ReportProgress(op, default); op.Progress = ReportProgress; var buf = await op; var file = await folder.CreateFileAsync(item.name, CreationCollisionOption.ReplaceExisting); await FileIO.WriteBufferAsync(file, buf); this.currentDownloaded += item.size; files.Add(file); } foreach (var item in files) { fileLaunched = fileLaunched || await Launcher.LaunchFileAsync(item); } } finally { if ((assets.Count > 1 || !fileLaunched) && !await Launcher.LaunchFolderAsync(folder)) { throw new InvalidOperationException("Launch download folder failed."); } } } } catch { await Launcher.LaunchUriAsync(new Uri(this.release.html_url)); } finally { def.Complete(); Application.Current.Exit(); } }
private async Task<IStorageFile> CreateToDownloadFolderAsync(string targetFileName, string defaultDownloadFolder = "PDF_Download") { var folder = await DownloadsFolder.CreateFolderAsync(defaultDownloadFolder, CreationCollisionOption.OpenIfExists); var file = await folder.CreateFileAsync(targetFileName, CreationCollisionOption.ReplaceExisting); return file; }