private void OnBeforeAccess(TokenCacheNotificationArgs args) { IStorageFile cacheFile = ApplicationData.Current.LocalFolder.TryGetItemAsync(CacheFileName) .AsTask().GetAwaiter().GetResult() as IStorageFile; if (cacheFile != null) { byte[] decryptedBlob = null; try { decryptedBlob = ReadAndDecrypt(cacheFile); } catch (Exception ex) { _logger.Error("The UWP cache file could not be decrypted. Corrupted files cannot be restored. Deleting the file."); _logger.ErrorPii(ex); cacheFile.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().GetAwaiter().GetResult(); return; } if (decryptedBlob != null) { args.TokenCache.DeserializeMsalV3(decryptedBlob); } } }
internal override void Delete(StorageTransmission item) { try { if (this.StorageFolder == null) { return; } // Initial storage size calculation. this.EnsureSizeIsCalculatedAsync().ConfigureAwait(false).GetAwaiter().GetResult(); IStorageFile file = this.StorageFolder.GetFileAsync(item.FileName).AsTask().ConfigureAwait(false).GetAwaiter().GetResult(); long fileSize = this.GetSizeAsync(file).ConfigureAwait(false).GetAwaiter().GetResult(); file.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().ConfigureAwait(false).GetAwaiter().GetResult(); this.deletedFilesQueue.Enqueue(item.FileName); // calculate size Interlocked.Add(ref this.storageSize, -fileSize); Interlocked.Decrement(ref this.storageCountFiles); } catch (IOException e) { string msg = string.Format(CultureInfo.InvariantCulture, "Failed to delete a file. file: {0} Exception: {1}", item == null ? "null" : item.FullFilePath, e); CoreEventSource.Log.LogVerbose(msg); } }
private static async Task destroyAllDBFiles(string dbDirPath, string dirName, Boolean destroyAll, string username) { var dbDir = await ApplicationData.Current.LocalFolder.GetFolderAsync(dirName); if (dbDir.Path == dbDirPath) { StorageFolder dbDirectory = await StorageFolder.GetFolderFromPathAsync(dbDirPath); if (destroyAll) { IEnumerable <IStorageFile> files = await dbDirectory.GetFilesAsync(); foreach (IStorageFile anyfile in files) { try { await anyfile.DeleteAsync(); } catch (Exception) { //log error message } } } else { IStorageFile file = await dbDirectory.GetFileAsync(username + DB_PATH_EXT); try { await file.DeleteAsync(); } catch (Exception) { } } } }
private async void toggleSwitch_Toggled(object sender, RoutedEventArgs e) { StorageFolder webFolder = await localFolder.GetFolderAsync("web"); IStorageFile namesave = await appFolder.CreateFileAsync("namesave", CreationCollisionOption.OpenIfExists); if (importSwitch.IsOn == true) { Windows.Storage.Pickers.FileOpenPicker openPicker = new Windows.Storage.Pickers.FileOpenPicker(); //openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; //openPicker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; openPicker.FileTypeFilter.Clear(); openPicker.FileTypeFilter.Add(".html"); StorageFile updatefile = await openPicker.PickSingleFileAsync(); if (updatefile != null) { string updatename = updatefile.Name; Windows.Storage.Streams.IRandomAccessStream fileStream = await updatefile.OpenAsync(FileAccessMode.Read); await updatefile.CopyAsync(webFolder, updatename, NameCollisionOption.ReplaceExisting); //var buffer = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary( //updatename , Windows.Security.Cryptography.BinaryStringEncoding.Utf8); //await Windows.Storage.FileIO.WriteBufferAsync(namesave , buffer); await FileIO.WriteTextAsync(namesave, updatename, 0); text.Text = "已更新:" + updatename; Uri Uri = new Uri("ms-appx-web:///web/" + updatename); updateweb.Source = Uri; } else { string updatename = "index.html"; await FileIO.WriteTextAsync(namesave, updatename, 0); } } else { IStorageFile name = await appFolder.GetFileAsync("namesave"); string updatename = await FileIO.ReadTextAsync(name); //await localFolder.CreateFolderAsync("web", CreationCollisionOption.GenerateUniqueName); StorageFile restorefile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///originweb/" + updatename)); //string restorename = restorefile.Name; await restorefile.CopyAsync(webFolder, updatename, NameCollisionOption.ReplaceExisting); Uri Uri = new Uri("ms-appx-web:///web/" + updatename); updateweb.Source = Uri; await namesave.DeleteAsync(); text.Text = "已还原:" + updatename; } }
public bool CancelDownloading(Uri uri) { bool bRes = false; #if UNITY_WSA && ENABLE_WINMD_SUPPORT if (_operations.ContainsKey(uri)) { bRes = true; DownloadOperation oper = _operations[uri].operation; IStorageFile file = oper.ResultFile; CancellationTokenSource canceledToken = new CancellationTokenSource(); canceledToken.Cancel(); oper.AttachAsync().AsTask(canceledToken.Token).ContinueWith((task) => { if (file != null) { try { file.DeleteAsync(); } catch { } } }); _operations.Remove(uri); } #endif return(bRes); }
private async void Button_Click(object sender, RoutedEventArgs e) { try { Button button = sender as Button; Model.Download Vediodata = button.DataContext as Model.Download; sqliteHelper.DeleteData(Vediodata); string sql = "delete from sqlite_sequence where name='Download';"; sqliteHelper.UpadateData(sql); DownloadList.Remove(Vediodata); if (DownloadList.Count == 0) { TB.Opacity = 1; } else { TB.Opacity = 0; } string FileName = Vediodata.video_uri; string[] str = FileName.Split('/'); string filename = str[str.Length - 1]; IStorageFolder Folder = ApplicationData.Current.LocalCacheFolder; IStorageFile File = await Folder.GetFileAsync(filename); await File.DeleteAsync(); } catch (Exception) { var dialog = new MessageDialog("删除时出错", "yoho"); dialog.Commands.Add(new UICommand("确定", cmd => { })); await dialog.ShowAsync(); } }
private static async Task <IEnumerable <ReportItem> > GetSpooledReportsAsync() { IStorageFile file = null; try { file = await ApplicationData.Current.TemporaryFolder.GetFileAsync(BackgroundSyncTask.SpoolFilename); } catch (FileNotFoundException) { return(null); } // load... try { var json = await FileIO.ReadTextAsync(file); return(JsonConvert.DeserializeObject <IEnumerable <ReportItem> >(json)); } finally { // delete the file - we have to do this regardless, but we can't await here... file.DeleteAsync(); } }
private async void ClearButton_Click(object sender, RoutedEventArgs e) { var dig = new MessageDialog("若应用无法使用,请尝试清除数据,清除数据后会应用将返回登陆界面。\n\n是否继续?", "警告"); var btnOk = new UICommand("是"); dig.Commands.Add(btnOk); var btnCancel = new UICommand("否"); dig.Commands.Add(btnCancel); var result = await dig.ShowAsync(); if (null != result && result.Label == "是") { appSetting.Values.Clear(); IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder; IStorageFile storageFileWR = await applicationFolder.CreateFileAsync("kb", CreationCollisionOption.OpenIfExists); try { await storageFileWR.DeleteAsync(); } catch (Exception) { Debug.WriteLine("设置 -> 重置应用异常"); } //Application.Current.Exit(); Frame rootFrame = Window.Current.Content as Frame; rootFrame.Navigate(typeof(LoginPage)); } else if (null != result && result.Label == "否") { } }
private async Task HandleSuccessfullDownload(SignalAttachment attachment, IStorageFile tmpDownload, DownloadOperation download) { try { SemaphoreSlim.Wait(CancelSource.Token); StorageFile plaintextFile = await ApplicationData.Current.LocalCacheFolder.CreateFileAsync(@"Attachments\" + attachment.Id + ".plain", CreationCollisionOption.ReplaceExisting); using (var tmpFileStream = (await tmpDownload.OpenAsync(FileAccessMode.ReadWrite)).AsStream()) using (var plaintextFileStream = (await plaintextFile.OpenAsync(FileAccessMode.ReadWrite)).AsStream()) { Logger.LogInformation("Decrypting to {0}\\{1}", plaintextFile.Path, plaintextFile.Name); DecryptAttachment(attachment.ToAttachmentPointer(), tmpFileStream, plaintextFileStream); } Logger.LogInformation("Deleting tmpFile {0}", tmpDownload.Name); await tmpDownload.DeleteAsync(); attachment.Status = SignalAttachmentStatus.Finished; SignalDBContext.UpdateAttachmentStatus(attachment); await DispatchAttachmentStatusChanged(download, attachment); } catch (Exception e) { Logger.LogError("HandleSuccessfullDownload failed: {0}\n{1}", e.Message, e.StackTrace); } finally { if (Downloads.ContainsKey(attachment.Id)) { Downloads.Remove(attachment.Id); } SemaphoreSlim.Release(); } }
protected override async void OnNavigatedFrom(NavigationEventArgs e) { //delete the temporary zip file if (tempZipFile != null) { await tempZipFile.DeleteAsync(); } base.OnNavigatedFrom(e); }
public async Task DeleteAsync(CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); await EnsureExistsAsync(cancellationToken); await _storageFile.DeleteAsync() .AsTask(cancellationToken) .ConfigureAwait(false); }
/// <summary> /// 删除文件 /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static async Task DeleteFileAsync(string filePath) { var x = await IsExistFileAsync(filePath); if (x) { IStorageFile file = await GetFileAccess(filePath); await file.DeleteAsync(); } }
public static async Task TryDeleteFileAsync(IStorageFile file) { try { await file.DeleteAsync(); } catch { // ignored } }
public void Dispose() { MessageBus.Unsubscribe(this, MessageBus_OnDelivery); if (PreviewFile != null) { try { var j = PreviewFile.DeleteAsync(); } catch (Exception) { } } }
/// <summary> /// Moves a file to the recycle bin or deletes it permanently when specified or the recycle bin is not available. /// </summary> /// <param name="file">File to delete, usually specified via extension.</param> /// <param name="permanent"> /// True to delete permanently, otherwise it is moved to the recycle bin when available. /// Default is false (recycle). /// </param> public static void Delete(this IStorageFile file, bool permanent) { // Validate if (file == null) { throw new ArgumentNullException("file"); } // Call overloaded method with appropriate delete option file.DeleteAsync(permanent ? StorageDeleteOption.PermanentDelete : StorageDeleteOption.Default).GetAwaiter(); }
private async void AppBarButton_Click(object sender, RoutedEventArgs e) { appSetting.Values.Remove("idNum"); IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder; IStorageFile storageFileWR = await applicationFolder.CreateFileAsync("kb", CreationCollisionOption.OpenIfExists); try { await storageFileWR.DeleteAsync(); } catch (Exception) { Debug.WriteLine("个人 -> 切换账号删除课表数据异常"); } Frame.Navigate(typeof(LoginPage)); }
internal static async Task DeleteSRAMFile(ROMDBEntry re) { string sramName = re.FileName.Substring(0, re.FileName.LastIndexOf('.')) + ".sav"; StorageFolder localFolder = ApplicationData.Current.LocalFolder; StorageFolder romFolder = await localFolder.GetFolderAsync(ROM_DIRECTORY); StorageFolder saveFolder = await romFolder.GetFolderAsync(SAVE_DIRECTORY); try { IStorageFile file = await saveFolder.GetFileAsync(sramName); await file.DeleteAsync(); } catch (Exception) { } }
/// <summary> /// Moves the current file to the location of the specified file and replaces the specified file in that location. /// </summary> /// <param name="fileToReplace">The file to replace.</param> /// <returns>No object or value is returned by this method.</returns> public Task MoveAndReplaceAsync(IStorageFile fileToReplace) { if (fileToReplace == null) { throw new ArgumentNullException("fileToReplace"); } #if WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP || WINDOWS_PHONE return(_file.MoveAndReplaceAsync((Windows.Storage.StorageFile)((StorageFile)fileToReplace)).AsTask()); #elif __ANDROID__ || __UNIFIED__ || WIN32 || TIZEN return(Task.Run(async() => { string fileName = fileToReplace.Name; string folder = global::System.IO.Path.GetDirectoryName(fileToReplace.Path); await fileToReplace.DeleteAsync(); await MoveAsync(await StorageFolder.GetFolderFromPathAsync(folder), fileName); })); #else throw new PlatformNotSupportedException(); #endif }
private async void SwitchAppBarButton_Click(object sender, RoutedEventArgs e) { //appSetting.Values.Remove("idNum"); try { var vault = new Windows.Security.Credentials.PasswordVault(); var credentialList = vault.FindAllByResource(resourceName); foreach (var item in credentialList) { vault.Remove(item); } } catch { } appSetting.Values["CommunityPerInfo"] = false; appSetting.Values["isUseingBackgroundTask"] = false; IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder; IStorageFile storageFileWR = await applicationFolder.CreateFileAsync("kb", CreationCollisionOption.OpenIfExists); try { await storageFileWR.DeleteAsync(); if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.UI.StartScreen.JumpList")) { if (JumpList.IsSupported()) { DisableSystemJumpListAsync(); } } } catch (Exception) { Debug.WriteLine("个人 -> 切换账号删除课表数据异常"); } Frame rootFrame = Window.Current.Content as Frame; rootFrame.Navigate(typeof(LoginPage)); }
private async Task <bool> DownloadImageAsync(IStorageFolder folder, string desiredName, Uri imageUri) { #region Check parameter if (folder == null || desiredName == string.Empty || imageUri == null) { throw new ArgumentException(_service.DataServiceName + " - DownloadImageAsync methods."); } #endregion try { using (HttpClient client = new HttpClient()) { IBuffer buffer = await client.GetBufferAsync(imageUri); IStorageFile file = await folder.CreateFileAsync(desiredName, CreationCollisionOption.ReplaceExisting); try { await FileIO.WriteBufferAsync(file, buffer); } catch (Exception) { await file.DeleteAsync(StorageDeleteOption.PermanentDelete); return(false); } } } catch (Exception ex) { Debug.WriteLine("DownloadImageAsync method - " + desiredName + " error: ", ex.Message); return(false); } return(true); }
public async Task DeleteFileAsync(IStorageFile backingFile, FileLocation location) { if (!_initialized) { throw new ServiceNotInitializedException($"{nameof(FileService)} was not initialized before access was attempted."); } using (await f_lock.Acquire()) { string fileName = backingFile.Name; var collectionToSearch = location == FileLocation.Local ? LocalFiles : RoamedFiles; collectionToSearch.Remove(collectionToSearch.Single(x => x.BackingFile == backingFile)); try { await backingFile.DeleteAsync(StorageDeleteOption.PermanentDelete); } catch (Exception ex) { Debug.WriteLine("Failed to delete file: " + ex); } await _ivService.Remove(GetParentFolder(backingFile), location); } }
/// <summary> /// Moves the current file to the location of the specified file and replaces the specified file in that location. /// </summary> /// <param name="fileToReplace">The file to replace.</param> /// <returns>No object or value is returned by this method.</returns> public Task MoveAndReplaceAsync(IStorageFile fileToReplace) { if(fileToReplace == null) { throw new ArgumentNullException("fileToReplace"); } #if WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP || WINDOWS_PHONE return _file.MoveAndReplaceAsync((Windows.Storage.StorageFile)((StorageFile)fileToReplace)).AsTask(); #elif __ANDROID__ || __UNIFIED__ || WIN32 || TIZEN return Task.Run(async () => { string fileName = fileToReplace.Name; string folder = global::System.IO.Path.GetDirectoryName(fileToReplace.Path); await fileToReplace.DeleteAsync(); await MoveAsync(await StorageFolder.GetFolderFromPathAsync(folder), fileName); }); #else throw new PlatformNotSupportedException(); #endif }
/// <summary> /// Deletes the file /// </summary> /// <returns>A task which will complete after the file is deleted.</returns> public async Task DeleteAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); await _wrappedFile.DeleteAsync().AsTask(cancellationToken).ConfigureAwait(false); }
/// <summary> /// Updates the id3 tags. WARNING, there needs to be more testing with lower end devices. /// </summary> /// <param name="song">The song.</param> /// <param name="file">The file.</param> private async Task <bool> UpdateId3TagsAsync(Song song, IStorageFile file) { using (var fileStream = await file.OpenStreamForWriteAsync().ConfigureAwait(false)) { TagLib.File tagFile; try { tagFile = TagLib.File.Create(new SimpleFileAbstraction(file.Name, fileStream, fileStream)); } catch (CorruptFileException) { await CollectionHelper.DeleteEntryAsync(song); await file.DeleteAsync(); return(false); } catch { return(false); } var newTags = tagFile.GetTag(TagTypes.Id3v2, true); newTags.Title = song.Name; if (song.Artist.ProviderId != "autc.unknown") { newTags.Performers = song.ArtistName.Split(',').Select(p => p.Trim()).ToArray(); } newTags.Album = song.Album.Name; newTags.AlbumArtists = new[] { song.Album.PrimaryArtist.Name }; if (!string.IsNullOrEmpty(song.Album.Genre)) { newTags.Genres = song.Album.Genre.Split(',').Select(p => p.Trim()).ToArray(); } newTags.Track = (uint)song.TrackNumber; newTags.MusicIpId = song.RadioId.ToString(); newTags.MusicBrainzTrackId = song.CloudId; newTags.Comment = "Downloaded by airstem for Windows 10."; try { if (song.Album.HasArtwork) { var albumFilePath = string.Format(AppConstant.ArtworkPath, song.Album.Id); var artworkFile = await StorageHelper.GetFileAsync(albumFilePath).ConfigureAwait(false); using (var artworkStream = await artworkFile.OpenAsync(PCLStorage.FileAccess.Read)) { using (var memStream = new MemoryStream()) { await artworkStream.CopyToAsync(memStream); newTags.Pictures = new IPicture[] { new Picture( new ByteVector( memStream.ToArray(), (int)memStream.Length)) }; } } } } catch (UnauthorizedAccessException) { ToastManager.ShowError("UnauthorizedAccess Exception."); // Should never happen, since we are opening the files in read mode and nothing is locking it. } await Task.Run(() => tagFile.Save()); return(true); } }
/// <summary> /// Deletes the file /// </summary> /// <returns>A task which will complete after the file is deleted.</returns> public async Task DeleteAsync() { await _wrappedFile.DeleteAsync().AsTask().ConfigureAwait(false); }
private async Task ContinueAfterFilePickAsync(IStorageFile file, IStorageFolder directory, Folder folder, Wallet parentWallet, bool deleteFile = false) { bool isImported = false; try { if (directory != null && file != null && await file.GetFileSizeAsync().ConfigureAwait(false) <= ConstantData.MAX_IMPORTABLE_MEDIA_FILE_SIZE) { _animationStarter.StartAnimation(AnimationStarter.Animations.Updating); StorageFile newFile = await file.CopyAsync(directory, file.Name, NameCollisionOption.GenerateUniqueName).AsTask().ConfigureAwait(false); if (parentWallet == null) { isImported = await folder.ImportMediaFileIntoNewWalletAsync(newFile).ConfigureAwait(false); } else { isImported = await parentWallet.ImportFileAsync(newFile).ConfigureAwait(false); } if (!isImported) { // delete the copied file if something went wrong if (newFile != null) await newFile.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().ConfigureAwait(false); Logger.Add_TPL("isImported = false", Logger.AppEventsLogFilename, Logger.Severity.Info); } // delete the original file if it was a photo taken with CameraCaptureUI if (deleteFile) await file.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().ConfigureAwait(false); } } catch (Exception ex) { await Logger.AddAsync(ex.ToString(), Logger.AppEventsLogFilename).ConfigureAwait(false); } _animationStarter.EndAllAnimations(); _animationStarter.StartAnimation(isImported ? AnimationStarter.Animations.Success : AnimationStarter.Animations.Failure); IsImportingMedia = false; }
private async void ClearButton_Click(object sender, RoutedEventArgs e) { var dig = new MessageDialog("若应用无法使用,请尝试清除数据,清除数据后会应用将返回登陆界面。\n\n是否继续?", "警告"); var btnOk = new UICommand("是"); dig.Commands.Add(btnOk); var btnCancel = new UICommand("否"); dig.Commands.Add(btnCancel); var result = await dig.ShowAsync(); if (null != result && result.Label == "是") { try { appSetting.Values.Clear(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } DelectRemind(); try { var vault = new Windows.Security.Credentials.PasswordVault(); var credentialList = vault.FindAllByResource(resourceName); foreach (var item in credentialList) { vault.Remove(item); } } catch { } appSetting.Values["CommunityPerInfo"] = false; appSetting.Values["isUseingBackgroundTask"] = false; IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder; IStorageFile storageFileWR = await applicationFolder.CreateFileAsync("kb", CreationCollisionOption.OpenIfExists); try { await storageFileWR.DeleteAsync(); if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.UI.StartScreen.JumpList")) { if (JumpList.IsSupported()) { DisableSystemJumpListAsync(); } } } catch (Exception) { Debug.WriteLine("个人 -> 切换账号删除课表数据异常"); } try { await storageFileWR.DeleteAsync(); } catch (Exception error) { Debug.WriteLine(error.Message); Debug.WriteLine("设置 -> 重置应用异常"); } //Application.Current.Exit(); Frame rootFrame = Window.Current.Content as Frame; rootFrame.Navigate(typeof(LoginPage)); } else if (null != result && result.Label == "否") { } }
public Task DeleteAsync() { return(_storageFile.DeleteAsync().AsTask()); }