private IAsyncOperation<StorageFile> SaveFileAsync( SaveFileInteraction saveFile ) { Contract.Requires( saveFile != null ); Contract.Ensures( Contract.Result<IAsyncOperation<StorageFile>>() != null ); var dialog = new FileSavePicker(); dialog.DefaultFileExtension = saveFile.DefaultFileExtension; dialog.FileTypeChoices.AddRange( saveFile.FileTypeChoices.ToDictionary() ); dialog.SuggestedStartLocation = SuggestedStartLocation; if ( !string.IsNullOrEmpty( saveFile.FileName ) ) dialog.SuggestedFileName = saveFile.FileName; if ( !string.IsNullOrEmpty( SettingsIdentifier ) ) dialog.SettingsIdentifier = SettingsIdentifier; return dialog.PickSaveFileAsync(); }
private async void Save_Click(object sender, RoutedEventArgs e) { this.currentMenber.useName = this.UseName.Text; this.currentMenber.email = this.Email.Text; this.currentMenber.phone = this.Phone.Text; string jsonMember = JsonConvert.SerializeObject(this.currentMenber); string useName = UseName.Text; string email = Email.Text; FileSavePicker savePicker = new FileSavePicker(); savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; savePicker.FileTypeChoices.Add("Plain Text", new List <string>() { ".txt" }); savePicker.SuggestedFileName = "New Document"; StorageFile File = await savePicker.PickSaveFileAsync(); await FileIO.WriteTextAsync(File, jsonMember); }
public static async Task <StorageFile> SaveFile(KeyValuePair <string, IList <string> > fileTypes, string suggestedFileName = null) { try { var fileSavePicker = new FileSavePicker() { SuggestedFileName = suggestedFileName ?? string.Empty, SuggestedStartLocation = PickerLocationId.ComputerFolder, }; fileSavePicker.FileTypeChoices.Add(fileTypes); return(await fileSavePicker.PickSaveFileAsync()); } catch (Exception e) { await DialogService.ShowAlertAsync( ResourceService.AppMessages.GetString("AM_SelectFileFailed_Title"), string.Format(ResourceService.AppMessages.GetString("AM_SelectFileFailed"), e.Message)); return(null); } }
private async Task SaveIt() //Implement The Saving Mechanism { try { FileSavePicker fileSave = new FileSavePicker(); //Insantiating a fileSave Object In Order To Save The Drawn Object fileSave.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; //Picking A Start Location For Choosing Where To Save fileSave.DefaultFileExtension = ".png"; //Setting The Default FileFormat To png fileSave.FileTypeChoices.Add("PNG", new String[] { ".png" }); //Adding PNG To The File Type Choice StorageFile storage = await fileSave.PickSaveFileAsync(); using (IOutputStream fileStream = await storage.OpenAsync(FileAccessMode.ReadWrite)) { if (fileStream != null) { await inkManager.SaveAsync(fileStream); } } } catch (Exception ex) { } }
private async void SaveLink_OnClick(object sender, RoutedEventArgs e) { var vm = (CommandProfileProviderViewModel)DataContext; var link = await vm.GetUrlAsync(); if (!link.Item1) { await new MessageDialog(link.Item2, I18N.Translate("InvalidInput")).ShowAsync(); return; } var content = ProfileProviderViewModelBase.GetShortcutFileContent(link.Item2); FileSavePicker savePicker = new FileSavePicker { SuggestedStartLocation = PickerLocationId.Desktop }; savePicker.FileTypeChoices.Add("Shortcut", new List <string> { ".url" }); StorageFile file = await savePicker.PickSaveFileAsync(); if (file == null) { return; } try { await _trayProcessCommunicationService.SaveTextFileAsync(file.Path, content); } catch (Exception ex) { await new MessageDialog(ex.Message, I18N.Translate("Error")).ShowAsync(); } }
private async void SaveImageButtonClicked(object sender, RoutedEventArgs e) { await SaveStrokesToBitmap(mImage); FileSavePicker savePicker = new FileSavePicker(); savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; savePicker.FileTypeChoices.Add("bmp Image", new List <string>() { ".bmp" }); savePicker.SuggestedFileName = "inkImage"; StorageFile f = await savePicker.PickSaveFileAsync(); if (f != null) { using (Stream stream = await f.OpenStreamForWriteAsync()) { await mImage.ToStream(stream.AsRandomAccessStream(), BitmapEncoder.BmpEncoderId); } } }
private static async Task <StorageFile> PickVideoAsync() { try { var picker = new FileSavePicker(); var time = DateTime.Now.ToString("yyyy-MM-dd-HHmmss"); picker.SuggestedStartLocation = PickerLocationId.VideosLibrary; picker.SuggestedFileName = $"recordedVideo{time}"; picker.DefaultFileExtension = ".mp4"; picker.FileTypeChoices.Add("MP4 Video", new List <string> { ".mp4" }); var file = await picker.PickSaveFileAsync(); return(file); } catch { return(null); } }
private async void JSONExportClick(object sender, RoutedEventArgs e) { var _Picker = new FileSavePicker { SuggestedStartLocation = PickerLocationId.DocumentsLibrary, DefaultFileExtension = ".json", SuggestedFileName = "MarsUpdates", SettingsIdentifier = ".json" }; _Picker.FileTypeChoices.Add("json", new List <string> { ".json" }); var _File = await _Picker.PickSaveFileAsync(); if (_File == null) { return; } var serialized = JSONSerializer <ObservableCollection <WeatherReport> > .Serialize(viewModel.QueriedList); using (IRandomAccessStream fileStream = await _File.OpenAsync(FileAccessMode.ReadWrite)) { using (IOutputStream outputStream = fileStream.GetOutputStreamAt(0)) { using (DataWriter dataWriter = new DataWriter(outputStream)) { dataWriter.WriteBytes(serialized); await dataWriter.StoreAsync(); dataWriter.DetachStream(); } await outputStream.FlushAsync(); } } }
public static async Task PickAndSaveFile(byte[] data, IDictionary <string, string> filter, bool AllFileType, string sugguestedName = null) { if (data == null || (filter == null && !AllFileType)) { throw new ArgumentNullException(); } if (filter.Count == 0 && !AllFileType) { throw new Exception("筛选器内容为空"); } FileSavePicker picker = new FileSavePicker(); if (filter != null && filter.Count > 0) { foreach (var i in filter) { picker.FileTypeChoices.Add(i.Key, new List <string>() { i.Value }); } } if (AllFileType) { picker.FileTypeChoices.Add("所有文件", new List <string>() { "." }); } if (sugguestedName != null) { picker.SuggestedFileName = sugguestedName; } var file = await picker.PickSaveFileAsync(); await Task.Run(() => FileIO.WriteBufferAsync(file, CryptographicBuffer.CreateFromByteArray(data))); }
public async Task <Stream> OpenWrite(string name) { var ext = Path.GetExtension(name); var picker = new FileSavePicker { SuggestedFileName = name }; picker.FileTypeChoices.Add(ext, new List <string> { ext }); var file = await picker.PickSaveFileAsync(); if (file == null) { return(null); } await FileIO.WriteTextAsync(file, string.Empty); var stream = await file.OpenStreamForWriteAsync().ConfigureAwait(false); return(stream); }
private async void SaveResults(object sender, RoutedEventArgs e) { var picker = new FileSavePicker(); picker.FileTypeChoices.Add("Comma-Separated Values (CSV)", new List <String> { ".csv" }); var file = await picker.PickSaveFileAsync(); if (file != null) { try { await SaveCSV(file); await Notify("Save successful."); } catch { await Notify("An error occurred during the save process."); } } }
/// <summary> /// Displays a save file dialog to the user. /// </summary> /// <param name="commitButtonText">The text, that is displayed on the commit button, that the user has to press to select a file.</param> /// <param name="fileTypeChoices">The file type filter, which determines which kinds of files are available to the user.</param> /// <param name="suggestedSaveFile">The file which is suggested to the user as the file to which he is saving.</param> /// <param name="suggestedStartLocation">The suggested start location, which is initally displayed by the save file dialog.</param> /// <returns>Returns the dialog result with the file that was selected by the user.</returns> public virtual async Task <DialogResult <StorageFile> > ShowSaveFileDialogAsync(string commitButtonText, IEnumerable <FileTypeRestriction> fileTypeChoices, StorageFile suggestedSaveFile, PickerLocationId suggestedStartLocation) { // Creates a new task completion source for the result of the save file dialog TaskCompletionSource <StorageFile> taskCompletionSource = new TaskCompletionSource <StorageFile>(); // Executes the save file dialog on the dispatcher thread of the current core application view, this is needed so that the code is always executed on the UI thread await CoreApplication.GetCurrentView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { // Creates a new save file dialog FileSavePicker fileSavePicker = new FileSavePicker { CommitButtonText = commitButtonText, SuggestedStartLocation = suggestedStartLocation }; if (suggestedSaveFile != null) { fileSavePicker.SuggestedSaveFile = suggestedSaveFile; } foreach (FileTypeRestriction fileTypeRestriction in fileTypeChoices) { fileSavePicker.FileTypeChoices.Add(fileTypeRestriction.FileTypesDescription, fileTypeRestriction.FileTypes.Select(fileType => fileType == "*" ? fileType : $".{fileType}").ToList()); } // Shows the save file dialog and stores the result taskCompletionSource.TrySetResult(await fileSavePicker.PickSaveFileAsync()); }); // Checks if the user cancelled the save file dialog, if so then cancel is returned, otherwise okay is returned with the file that was picked by the user StorageFile storageFile = await taskCompletionSource.Task; if (storageFile == null) { return(new DialogResult <StorageFile>(DialogResult.Cancel, null)); } else { return(new DialogResult <StorageFile>(DialogResult.Okay, storageFile)); } }
/// <summary> /// Save InkCanvas strokes to .ink File /// </summary> /// <param name="inkCanvas">InkCanvas Object</param> /// <param name="location">PickerLocationId</param> /// <returns>Success or not</returns> public static async Task <Response> SaveToInkFile(InkCanvas inkCanvas, PickerLocationId location) { var picker = new FileSavePicker { SuggestedStartLocation = location }; picker.FileTypeChoices.Add("INK files", new List <string> { ".ink" }); var file = await picker.PickSaveFileAsync(); if (file == null) { return(new Response { IsSuccess = false, Message = $"{nameof(file)} is null" }); } return(await SaveToStorageFile(inkCanvas, file)); }
/// <summary> /// Launch file picker for user to select a file and save a VideoFrame to it /// </summary> /// <param name="frame"></param> /// <returns></returns> public static IAsyncAction SaveVideoFrameToFilePickedAsync(VideoFrame frame) { return(AsyncInfo.Run(async(token) => { // Trigger file picker to select an image file FileSavePicker fileSavePicker = new FileSavePicker(); fileSavePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; fileSavePicker.FileTypeChoices.Add("image file", new List <string>() { ".jpg" }); fileSavePicker.SuggestedFileName = "NewImage"; StorageFile selectedStorageFile = await fileSavePicker.PickSaveFileAsync(); if (selectedStorageFile == null) { return; } using (IRandomAccessStream stream = await selectedStorageFile.OpenAsync(FileAccessMode.ReadWrite)) { VideoFrame frameToEncode = frame; BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); if (frameToEncode.SoftwareBitmap == null) { Debug.Assert(frame.Direct3DSurface != null); frameToEncode = new VideoFrame(BitmapPixelFormat.Bgra8, frame.Direct3DSurface.Description.Width, frame.Direct3DSurface.Description.Height); await frame.CopyToAsync(frameToEncode); } encoder.SetSoftwareBitmap( frameToEncode.SoftwareBitmap.BitmapPixelFormat.Equals(BitmapPixelFormat.Bgra8) ? frameToEncode.SoftwareBitmap : SoftwareBitmap.Convert(frameToEncode.SoftwareBitmap, BitmapPixelFormat.Bgra8)); await encoder.FlushAsync(); } })); }
/// <summary> /// Creates a save dialog and saves the landscape into the file /// </summary> public async Task SaveDialog() { LandscapeBuilder landscapeBuilder = BuildLandscapeBuilder(); if (landscapeBuilder.IsValid()) { FileSavePicker savePicker = new FileSavePicker { SuggestedStartLocation = PickerLocationId.DocumentsLibrary }; savePicker.FileTypeChoices.Add("Landscape XML", new List <string>() { ".xml" }); savePicker.SuggestedFileName = "New Landscape"; StorageFile file = await savePicker.PickSaveFileAsync(); await Save(file, landscapeBuilder); } else { await Task.Run(Run); } }
private async void ButtonOpenCSV_Clonk(object sender, RoutedEventArgs e) { FileSavePicker open = new FileSavePicker(); open.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; open.FileTypeChoices.Add("Archivos de Excel", new List <String>() { ".csv" }); open.SuggestedFileName = "MuestraBanda"; archivo = await open.PickSaveFileAsync(); if (archivo != null) { TextBoxRutaCSV.Text = archivo.Name; CachedFileManager.DeferUpdates(archivo); } else { TextBoxRutaCSV.Text = "Imposible elegir archivo"; } }
public async void SaveFileButtonClick(object sender, RoutedEventArgs e) { FileSavePicker savePicker = new FileSavePicker(); savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; savePicker.FileTypeChoices.Add("ETL", new List <string>() { ".etl" }); savePicker.SuggestedFileName = "SensorExplorerLog"; StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { CachedFileManager.DeferUpdates(file); StorageFile logFileGenerated = await rootPage.loggingSessionView.CloseAndSaveToFileAsync(); await logFileGenerated.CopyAndReplaceAsync(file); FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file); if (status == FileUpdateStatus.Complete) { rootPage.NotifyUser("File " + file.Name + " was saved.", NotifyType.StatusMessage); } else if (status == FileUpdateStatus.CompleteAndRenamed) { rootPage.NotifyUser("File " + file.Name + " was renamed and saved.", NotifyType.StatusMessage); } else { rootPage.NotifyUser("File " + file.Name + " couldn't be saved.", NotifyType.ErrorMessage); } } else { rootPage.NotifyUser("Operation cancelled.", NotifyType.ErrorMessage); } }
public override async void Execute() { var sfp = new FileSavePicker(); sfp.FileTypeChoices.Add("图片文件", new List <string>() { ".bmp", ".png", ".jpg" }); sfp.SuggestedStartLocation = PickerLocationId.PicturesLibrary; var file = await sfp.PickSaveFileAsync(); if (file == null) { return; } var scvm = SimpleIoc.Default.GetInstance <SingleCanvasViewModel>(); Debug.Assert(scvm != null); await scvm.SaveInStreamAsync(await file.OpenAsync(FileAccessMode.ReadWrite)); NotificationManager.NotifyText("保存到文件失败"); }
private async void save_Click(object sender, RoutedEventArgs e) { var resources = ResourceLoader.GetForCurrentView("Controls"); var control = sender as Control; control.IsEnabled = false; try { var extension = Path.GetExtension(Embed.Thumbnail.Url.ToString()); var fileName = Path.GetFileNameWithoutExtension(Embed.Thumbnail.Url.ToString()); var picker = new FileSavePicker() { SuggestedStartLocation = PickerLocationId.Downloads, SuggestedFileName = fileName, DefaultFileExtension = extension }; picker.FileTypeChoices.Add(string.Format(resources.GetString("AttachmentExtensionFormat"), extension), new List <string>() { extension }); var file = await picker.PickSaveFileAsync(); if (file != null) { await Tools.DownloadToFileAsync(Embed.Thumbnail.Url, file); } } catch { await UIUtilities.ShowErrorDialogAsync( resources.GetString("AttachmentDownloadFailedTitle"), resources.GetString("AttachmentDownloadFailedText")); } control.IsEnabled = true; }
public async Task <bool> ExportSitesToUserInputTarget(DataSourceType preferredType = DataSourceType.Json) { var picker = new FileSavePicker { SuggestedFileName = $"mpw-export.{TypeToExtension(preferredType)}", SuggestedStartLocation = PickerLocationId.DocumentsLibrary }; if (preferredType == DataSourceType.Json) { picker.FileTypeChoices.Add("JSON", new List <string> { $".{TypeToExtension(DataSourceType.Json)}" }); picker.FileTypeChoices.Add("MPSites", new List <string> { $".{TypeToExtension(DataSourceType.MpSites)}" }); } if (preferredType == DataSourceType.MpSites) { picker.FileTypeChoices.Add("MPSites", new List <string> { $".{TypeToExtension(DataSourceType.MpSites)}" }); picker.FileTypeChoices.Add("JSON", new List <string> { $".{TypeToExtension(DataSourceType.Json)}" }); } var file = await picker.PickSaveFileAsync(); if (file == null) { return(false); } preferredType = ExtensionToType(file.Name); await _importer.Export(preferredType, file); _telemetry.LogMessage(this, message: $"{preferredType}"); return(true); }
public async void OnTakePhoto() { var cam = new CameraCaptureUI(); cam.PhotoSettings.AllowCropping = true; cam.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Png; cam.PhotoSettings.CroppedSizeInPixels = new Size(300, 300); StorageFile file = await cam.CaptureFileAsync(CameraCaptureUIMode.Photo); if (file != null) { var picker = new FileSavePicker(); picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; picker.FileTypeChoices.Add("Image File", new string[] { ".png" }); StorageFile fileDestination = await picker.PickSaveFileAsync(); if (fileDestination != null) { await file.CopyAndReplaceAsync(fileDestination); } } }
private async void saveButton_Click(object sender, RoutedEventArgs e) { var savePicker = new FileSavePicker(); // место для сохранения по умолчанию savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; // устанавливаем типы файлов для сохранения savePicker.FileTypeChoices.Add("Plain Text", new List <string>() { ".txt" }); // устанавливаем имя нового файла по умолчанию savePicker.SuggestedFileName = "New Document"; savePicker.CommitButtonText = "Сохранить"; var new_file = await savePicker.PickSaveFileAsync(); if (new_file != null) { await FileIO.WriteTextAsync(new_file, myTextBox.Text); } }
private async void saveFile_click(object sender, RoutedEventArgs e) { if (!chosenImage()) { var dialog = new MessageDialog("Brak zdjęcia do zapisu"); await dialog.ShowAsync(); return; } FileSavePicker savePicker = new FileSavePicker(); savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; savePicker.FileTypeChoices.Add("JPG File", new List <string>() { ".jpg" }); savePicker.SuggestedFileName = fileName_textBlock.Text.Substring(0, fileName_textBlock.Text.Length - 4) + "_contours"; StorageFile savefile = await savePicker.PickSaveFileAsync(); if (savefile == null) { return; } IRandomAccessStream stream = await savefile.OpenAsync(FileAccessMode.ReadWrite); BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); Stream pixelStream = WriteableBitmapMainImage.PixelBuffer.AsStream(); byte[] pixels = new byte[pixelStream.Length]; await pixelStream.ReadAsync(pixels, 0, pixels.Length); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)WriteableBitmapMainImage.PixelWidth, (uint)WriteableBitmapMainImage.PixelHeight, 96.0, 96.0, pixels); await encoder.FlushAsync(); }
async Task saveImage() { FileSavePicker picker = new FileSavePicker(); picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; picker.FileTypeChoices.Add(GetResourceString("GifFilePlain"), new List <string>() { ".gif" }); picker.SuggestedFileName = illust.Title; var file = await picker.PickSaveFileAsync(); if (file != null) { CachedFileManager.DeferUpdates(file); using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { await stream.WriteAsync(buffer); } var updateStatus = await CachedFileManager.CompleteUpdatesAsync(file); if (updateStatus != FileUpdateStatus.Complete) { var messageDialog = new MessageDialog(GetResourceString("SaveUgoiraFailedPlain")); messageDialog.Commands.Add(new UICommand(GetResourceString("RetryPlain"), async(a) => { await saveImage(); })); messageDialog.Commands.Add(new UICommand(GetResourceString("CancelPlain"))); messageDialog.DefaultCommandIndex = 0; messageDialog.CancelCommandIndex = 1; await messageDialog.ShowAsync(); } else { var messageDialog = new MessageDialog(GetResourceString("SaveUgoiraSucceededPlain")); messageDialog.Commands.Add(new UICommand(GetResourceString("OKPlain"))); messageDialog.DefaultCommandIndex = 0; await messageDialog.ShowAsync(); } } }
private async void SaveFileButton_Click(object sender, RoutedEventArgs e) { string text = PageTitle.Text; string description = Synopsis.Text; FileSavePicker savePicker = new FileSavePicker(); savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; List<string> plainTextFileTypes = new List<string>(new string[] { ".txt" }); List<string> wordTextFileTypes = new List<string>(new string[] { ".doc" }); savePicker.FileTypeChoices.Add(new KeyValuePair<string, IList<string>>("Plain Text", plainTextFileTypes)); savePicker.FileTypeChoices.Add(new KeyValuePair<string, IList<string>>("Word Text", wordTextFileTypes)); savePicker.SuggestedFileName = text; StorageFile saveFile = await savePicker.PickSaveFileAsync(); if (saveFile != null) { await Windows.Storage.FileIO.WriteTextAsync(saveFile, description); await new Windows.UI.Popups.MessageDialog("File Saved!").ShowAsync(); } }
private async void SaveFlyoutItem_Click(object sender, RoutedEventArgs e) { MimePart _item = (MimePart)(sender as FrameworkElement).DataContext; // https://docs.microsoft.com/en-us/windows/uwp/files/quickstart-save-a-file-with-a-picker var savePicker = new FileSavePicker(); savePicker.SuggestedStartLocation = PickerLocationId.Downloads; // Dropdown of file types the user can save the file as // http://stackoverflow.com/questions/17070908/how-can-i-accept-any-file-type-in-filesavepicker // The file is NOT saved in case of "All files" // savePicker.FileTypeChoices.Add("All files", new List<string>() { "." }); string _extension = _item.FileName.Substring(_item.FileName.LastIndexOf(".")); savePicker.FileTypeChoices.Add(_extension.ToUpper() + " File", new List <string>() { _extension }); // Default file name if the user does not type one in or select a file to replace // The filename must NOT include extention savePicker.SuggestedFileName = _item.FileName.Remove(_item.FileName.LastIndexOf(".")); StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { bool success = await MimePart2FileAsync(_item, file); if (!success) { var dlg = new ContentDialog() { Content = "File " + file.Name + " couldn't be saved.", CloseButtonText = "OK" }; await dlg.ShowAsync(); } } }
private async void PlayerSaveButton_Click(object sender, RoutedEventArgs e) { FileSavePicker fileSelector = new FileSavePicker { SuggestedStartLocation = PickerLocationId.DocumentsLibrary }; fileSelector.FileTypeChoices.Add("csv", new List <string>() { ".csv" }); fileSelector.SuggestedFileName = "Profile0"; StorageFile file = await fileSelector.PickSaveFileAsync(); //More safety needs to be added. Popups for exported and failed to export should also eventually appear. if (file != null) { CachedFileManager.DeferUpdates(file); String[] lines = SaveSystem.MakeSaveFile(App.PlayerList[PlayerExportComboBox.SelectedIndex]); await FileIO.WriteLinesAsync(file, lines); Windows.Storage.Provider.FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { //Yay it saved. WarningCD warning = new WarningCD("Alert", "File Successfully saved."); warning.Show(); } } else { WarningCD warning = new WarningCD("Error: File not found", "No file was selected."); warning.Show(); } SavePlayerPopup.IsOpen = false; }
private async void Download_Click(object sender, RoutedEventArgs e) { if (_list.SelectedItem is DriveItem driveItem) { try { GraphServiceClient graphClient = await GraphServiceHelper.GetGraphServiceClientAsync(); if (graphClient != null) { FileSavePicker picker = new FileSavePicker(); picker.FileTypeChoices.Add(AllFilesMessage, new List <string>() { driveItem.Name.Substring(driveItem.Name.LastIndexOf(".")) }); picker.SuggestedFileName = driveItem.Name; picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; StorageFile file = await picker.PickSaveFileAsync(); if (file != null) { using (Stream inputStream = await graphClient.Drives[_driveId].Items[driveItem.Id].Content.Request().GetAsync()) { using (Stream outputStream = await file.OpenStreamForWriteAsync()) { await inputStream.CopyToAsync(outputStream); } } } } } catch (Exception exception) { MessageDialog messageDialog = new MessageDialog(exception.Message); await messageDialog.ShowAsync(); } } }
private async void ExportToImage() { var picker = new FileSavePicker() { DefaultFileExtension = ".jpeg", }; picker.FileTypeChoices.Add("Jpeg files", new List <string>() { ".jpeg" }); picker.FileTypeChoices.Add("Bmp Files", new List <string>() { ".bmp" }); picker.FileTypeChoices.Add("PNG Files", new List <string>() { ".png" }); StorageFile file = await picker.PickSaveFileAsync(); if (file != null) { var fileExtension = file.FileType.Remove(0, 1); using (Stream stream = new MemoryStream()) { await barCode.SaveAsync(stream, (ImageFormat)Enum.Parse(typeof(ImageFormat), fileExtension, true)); using (Stream saveSteam = await file.OpenStreamForWriteAsync()) { stream.CopyTo(saveSteam); stream.Seek(0, SeekOrigin.Begin); saveSteam.Seek(0, SeekOrigin.Begin); saveSteam.Flush(); } } } }
/// <summary> /// 选择文件保存位置并进行下一步处理 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// private async void Save_Click(ContentDialog sender, ContentDialogButtonClickEventArgs args) { FileSavePicker picker = new FileSavePicker(); picker.FileTypeChoices.Add("JPEG image", new string[] { ".jpg" }); picker.FileTypeChoices.Add("PNG image", new string[] { ".png" }); picker.FileTypeChoices.Add("BMP image", new string[] { ".bmp" }); picker.DefaultFileExtension = ".png"; picker.SuggestedFileName = "Output Image"; picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; var file = await picker.PickSaveFileAsync(); if (file != null && !String.IsNullOrEmpty(LongSide.Text)) { uint longSide = uint.Parse(LongSide.Text); if (await LoadSaveFileAsync(_inputFile, file, longSide)) { MsgBox.Text = "压缩成功!" + file.Path; } else { MsgBox.Text = "压缩失败!"; } } else if (LongSide.Text == "") { uint longSide = Width; if (await LoadSaveFileAsync(_inputFile, file, longSide)) { MsgBox.Text = "压缩成功!文件保存在" + file.Path; } else { MsgBox.Text = "压缩失败!"; } } }
/// <summary> /// 保存图片到任意的文件夹 /// </summary> /// <returns>保存成功返回true,失败返回false</returns> public async Task<bool> SaveFileImage() { try { StorageFile storageFile = null; storageFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(ApiHelper.ComputeMD5(this.Source), CreationCollisionOption.ReplaceExisting); await FileIO.WriteBytesAsync(storageFile, bytes); FileSavePicker savePicker = new FileSavePicker(); savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; savePicker.FileTypeChoices.Add("图片类型", new List<string>() { ".gif" }); savePicker.SuggestedFileName = storageFile.Name; StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { CachedFileManager.DeferUpdates(file); await storageFile.CopyAndReplaceAsync(file);//, file.Name, NameCollisionOption.GenerateUniqueName); FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file); if (status == FileUpdateStatus.Complete) { return true; } else { return false; } } else { return false; } } catch { return false; } }