async System.Threading.Tasks.Task<Windows.Storage.StorageFile> CaptureAndSave(UIElement element) { // capture var bitmap = new Windows.UI.Xaml.Media.Imaging.RenderTargetBitmap(); await bitmap.RenderAsync(element); var picker = new Windows.Storage.Pickers.FileSavePicker { SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary, FileTypeChoices = { { "JPEG", new[] { ".jpg" } } }, SuggestedFileName = "Image", DefaultFileExtension = ".jpg", CommitButtonText = "Save", }; // save var file = await picker.PickSaveFileAsync(); using (var stream = await file.OpenStreamForWriteAsync()) { var pixel = await bitmap.GetPixelsAsync(); var dpi = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().LogicalDpi; var random = stream.AsRandomAccessStream(); var jpg = Windows.Graphics.Imaging.BitmapEncoder.JpegEncoderId; var encoder = await Windows.Graphics.Imaging.BitmapEncoder.CreateAsync(jpg, random); var format = Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8; var alpha = Windows.Graphics.Imaging.BitmapAlphaMode.Ignore; var width = (uint)bitmap.PixelWidth; var height = (uint)bitmap.PixelHeight; encoder.SetPixelData(format, alpha, width, height, dpi, dpi, pixel.ToArray()); await encoder.FlushAsync(); } return file; }
public ArticleViewModel(INavigationService navigationService) { this.navigationService = navigationService; this.dataService = SimpleIoc.Default.GetInstance<IDataService>(); this.roamingSettings = SimpleIoc.Default.GetInstance<IRoamingSettingsService>(); GetArticle(); this.ShowComments = new RelayCommand(() => { this.navigationService.Navigate(ViewsType.Comments); }); this.BackCommand = new RelayCommand<string>((s) => { this.navigationService.GoBack(); }); this.AddToFavorite = new RelayCommand(() => { this.roamingSettings.WriteToRoamingSettings(this.Article); }); this.ShowFavorite = new RelayCommand(() => { this.navigationService.Navigate(ViewsType.Favorite); }); this.SaveRanglist = new RelayCommand(async () => { try { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); var plainTextFileTypes = new List<string>(new string[] { ".txt" }); savePicker.FileTypeChoices.Add( new KeyValuePair<string, IList<string>>("Лист", plainTextFileTypes) ); var saveFile = await savePicker.PickSaveFileAsync(); if (saveFile != null) { StringBuilder text = new StringBuilder(); foreach (var item in this.Article.Ranglist) { text.AppendLine(item.Palce); } await Windows.Storage.FileIO.WriteTextAsync(saveFile, text.ToString()); await new Windows.UI.Popups.MessageDialog("Файлът е запазен.").ShowAsync(); } } catch(Exception e) { new MessageDialog("Файлът НЕ беше създаден успешно.").ShowAsync(); } }); }
public static async void SaveToFile() { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as savePicker.FileTypeChoices.Add("Javascript object", new List<string>() { ".json" }); savePicker.FileTypeChoices.Add("iCalendar", new List<string>() { ".ics" }); // Default file name if the user does not type one in or select a file to replace savePicker.SuggestedFileName = "Students_Assistent-data"; StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { CachedFileManager.DeferUpdates(file); // write to file if (file.ContentType == "text/calendar") await FileIO.WriteTextAsync(file, dataStore.ExportToiCalendar()); else if (file.FileType == ".json") await FileIO.WriteTextAsync(file, dataStore.ExportToJson()); Windows.Storage.Provider.FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { //this.textBlock.Text = "File " + file.Name + " was saved."; } else { //this.textBlock.Text = "File " + file.Name + " couldn't be saved."; } } }
public async Task<bool> BackupJson(string json) { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; savePicker.FileTypeChoices.Add("Json", new List<string>() { ".json" }); savePicker.SuggestedFileName = "PlanetsBackup"; Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { await Windows.Storage.FileIO.WriteTextAsync(file, json); return true; } else { return false; } }
async void OnSaveAsync(object sender, RoutedEventArgs e) { // We don't want to save an empty file if (InkCanvas.InkPresenter.StrokeContainer.GetStrokes().Count > 0) { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; savePicker.FileTypeChoices.Add("Gif with embedded ISF", new System.Collections.Generic.List<string> { ".gif" }); Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (null != file) { using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { await InkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream); } } } }
async void SavePDFFile(object sender, RoutedEventArgs e) { var filePicker = new Windows.Storage.Pickers.FileSavePicker(); filePicker.FileTypeChoices.Add("PDF文件", new List <string>(new string[] { ".pdf" })); filePicker.SuggestedFileName = "新文件"; StorageFile storageFile = await filePicker.PickSaveFileAsync(); if (storageFile != null) { var stream = await storageFile.OpenStreamForWriteAsync(); await _excel.SavePdf(stream); stream.Dispose(); Kit.Msg("导出成功!"); } }
private async Task <StorageFile> SelectFile(string defaultFileName, List <KeyValuePair <string, List <string> > > fileTypeList) { var picker = new Windows.Storage.Pickers.FileSavePicker { SuggestedFileName = defaultFileName, SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary, DefaultFileExtension = Path.GetExtension(defaultFileName) }; foreach (KeyValuePair <string, List <string> > keyValue in fileTypeList) { picker.FileTypeChoices.Add(keyValue.Key, keyValue.Value); } StorageFile file = await picker.PickSaveFileAsync(); return(file); }
private async void Export_Click(object sender, RoutedEventArgs e) { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; savePicker.FileTypeChoices.Add("Plain Text", new List <string>() { ".txt" }); savePicker.SuggestedFileName = "Export " + DateTime.Now.ToString("dd-MM-yyyy"); Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { await Windows.Storage.FileIO.WriteTextAsync(file, Helpers.Save.Mangas.Export(History)); } }
async void SaveCsvFile(object sender, RoutedEventArgs e) { var filePicker = new Windows.Storage.Pickers.FileSavePicker(); filePicker.FileTypeChoices.Add("CSV文件", new List <string>(new string[] { ".csv" })); filePicker.SuggestedFileName = "新文件"; StorageFile storageFile = await filePicker.PickSaveFileAsync(); if (storageFile != null) { var stream = await storageFile.OpenStreamForWriteAsync(); await _excel.SaveCSV(_excel.ActiveSheetIndex, stream, TextFileSaveFlags.AsViewed); stream.Dispose(); Kit.Msg("导出成功!"); } }
public void SaveFilePanelAsync(string title, string directory, string defaultName, ExtensionFilter[] extensions, Action <ItemWithStream> cb) { UnityEngine.WSA.Application.InvokeOnUIThread(async() => { var filePicker = new Windows.Storage.Pickers.FileSavePicker(); filePicker.SuggestedFileName = defaultName; foreach (var extension in extensions) { filePicker.FileTypeChoices.Add(extension.Name, extension.Extensions); } var file = await filePicker.PickSaveFileAsync(); var fileWithStream = new ItemWithStream() { Name = file.Name }; await Task.Run(() => cb(fileWithStream)); }, false); }
private async void BrowseButton_Click(object sender, RoutedEventArgs e) { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; savePicker.FileTypeChoices.Add("Disc Image File", new List <string>() { ".iso" }); savePicker.SuggestedFileName = "Windows.iso"; Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { PathTextBox.Text = file.Path; } }
private async void writeToFileAsync(String rawCsv) { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as savePicker.FileTypeChoices.Add("Plain Text", new List <string>() { ".csv" }); // Default file name if the user does not type one in or select a file to replace savePicker.SuggestedFileName = "Nowy csv"; Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { // Prevent updates to the remote version of the file until // we finish making changes and call CompleteUpdatesAsync. Windows.Storage.CachedFileManager.DeferUpdates(file); // write to file await Windows.Storage.FileIO.WriteTextAsync(file, rawCsv); // Let Windows know that we're finished changing the file so // the other app can update the remote version of the file. // Completing updates may require Windows to ask for user input. Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { Debug.WriteLine("File " + file.Name + " was saved."); } else { Debug.WriteLine("File " + file.Name + " was NOT saved."); } } else { Debug.WriteLine("Cancelled"); } }
// Save all recorded data. private async Task saveData(int sensorNumber = 1) { print("save initiated for sensor: "); print(sensorNumber.ToString()); var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.FileTypeChoices.Add("Plain Text", new List <string>() { ".txt" }); savePicker.SuggestedFileName = dateTextBox.Text + "_exp" + numberTextBox.Text + "_" + ((sensorNumber == 1) ? Name1.Text : Name2.Text); Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { Windows.Storage.CachedFileManager.DeferUpdates(file); // write to file await Windows.Storage.FileIO.WriteTextAsync(file, csv[sensorNumber - 1].ToString()); Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { if (sensorNumber == numBoards) { numberTextBox.Text = (Int32.Parse(numberTextBox.Text) + 1).ToString(); } else { saveData(sensorNumber + 1); } } else { //this.textBlock.Text = "File " + file.Name + " couldn't be saved."; } } else { //this.textBlock.Text = "Operation cancelled."; } }
/// <summary> /// Saves the clicked torrent /// </summary> /// <param name="clickedItem"></param> public async void OnTorrentSaveClick(Torrent clickedItem) { if (clickedItem.Link.StartsWith("magnet:")) { DisplayMagnetLinkSaveError(); } else { Uri address = new Uri(clickedItem.Link, UriKind.Absolute); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address); WebResponse response; try { response = await request.GetResponseAsync(); Stream stream = response.GetResponseStream(); var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.FileTypeChoices.Add("Torrent", new List <string>() { ".torrent" }); savePicker.SuggestedFileName = String.Join("", clickedItem.Title.Split(Path.GetInvalidFileNameChars())); Windows.Storage.StorageFile torrentfile = await savePicker.PickSaveFileAsync(); if (torrentfile != null) { await Windows.Storage.FileIO.WriteBytesAsync(torrentfile, ReadStream(stream)); } } catch (WebException e) { if (e.Message.Contains("302")) { var link = e.Response.Headers["Location"]; if (link.StartsWith("magnet:")) { DisplayMagnetLinkSaveError(); } } } } }
public static async void SaveToFile() { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as savePicker.FileTypeChoices.Add("Javascript object", new List <string>() { ".json" }); savePicker.FileTypeChoices.Add("iCalendar", new List <string>() { ".ics" }); // Default file name if the user does not type one in or select a file to replace savePicker.SuggestedFileName = "Students_Assistent-data"; StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { CachedFileManager.DeferUpdates(file); // write to file if (file.ContentType == "text/calendar") { await FileIO.WriteTextAsync(file, dataStore.ExportToiCalendar()); } else if (file.FileType == ".json") { await FileIO.WriteTextAsync(file, dataStore.ExportToJson()); } Windows.Storage.Provider.FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { //this.textBlock.Text = "File " + file.Name + " was saved."; } else { //this.textBlock.Text = "File " + file.Name + " couldn't be saved."; } } }
private async void ExportTilesButton_Click(object sender, RoutedEventArgs e) { if (_tileCanvas == null) { return; } // Read selected tiles var rawImage = _tileCanvas.ExportBytes(_tileCanvas.SelectedTiles()); if (rawImage == null) { Logging.WriteLogMessage("ExportTilesButton_Click -> Failed to read tile data"); return; } // Select output path var picker = new Windows.Storage.Pickers.FileSavePicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; picker.FileTypeChoices?.Add("PNG image", new[] { ".png" }); var file = await picker.PickSaveFileAsync().AsTask().NotNull(); if (file == null || !file.IsAvailable) { Logging.WriteLogMessage("ExportTilesButton_Click -> Failed to get output path"); return; } // Save raw image as a PNG file using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite).NotNull()) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream).NotNull(); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)rawImage.Width, (uint)rawImage.Height, 96.0, 96.0, rawImage.Data); await encoder.FlushAsync().NotNull(); } }
private async void OnSaveClick(object sender, RoutedEventArgs e) { bool saved = this.paused; this.paused = true; this.StartStopCharts(); Exception error = null; try { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as savePicker.FileTypeChoices.Add("CSV Files", new List <string>() { ".csv" }); savePicker.SuggestedFileName = AppResources.DefaultDataFileName; StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { using (var fileStream = await file.OpenStreamForWriteAsync()) { using (var writer = new StreamWriter(fileStream)) { model.WriteTo(writer); } } } } catch (Exception ex) { error = ex; } this.paused = saved; if (error != null) { await ShowError(error.Message, AppResources.ErrorSavingSnapshotCaption); } this.StartStopCharts(); }
/// <summary> /// Metoda zajmująca się eksportem danych do pliku. /// Ustawiany jest FileSavePicker, w tym rozszeżenie zapisywanego pliku, oraz jego sugerowana nazwa /// Następnie sprawdzany jest warunek wyboru scieżki i pliku. Jeżeli plik został wybrany następuje zapis. /// Jeżeli nie, metoda kończy się bez efektu. /// </summary> /// <param name="path">Nazwa pliku przekazywana przy kliknięciu przycisku wywołującego metodę.</param> public async void ExportToFile(string path) { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; savePicker.FileTypeChoices.Add("CSV (.csv)", new List <string>() { ".csv" }); savePicker.SuggestedFileName = path + ".csv"; //var storageFolder = KnownFolders.DocumentsLibrary; var file = await savePicker.PickSaveFileAsync(); if (file != null) { await FileIO.WriteTextAsync(file, Export()); } }
public static IEnumerator SaveFile(string title, string directory, string defaultName, string extension, byte[] bytes, Action <bool, string> callback) { var saved = false; string path = null; var pickerClosed = false; UnityEngine.WSA.Application.InvokeOnUIThread(async() => { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); // If you have an error on this line, just switch Unity to Android and then switch back to UWP. This helped me for Unity 2018.1. savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; savePicker.SuggestedFileName = defaultName; savePicker.FileTypeChoices.Add("Image", new System.Collections.Generic.List <string>() { '.' + extension }); var file = await savePicker.PickSaveFileAsync(); if (file != null) { path = file.Path; Windows.Storage.CachedFileManager.DeferUpdates(file); var buffer = Windows.Security.Cryptography.CryptographicBuffer.CreateFromByteArray(bytes); await Windows.Storage.FileIO.WriteBufferAsync(file, buffer); var status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); saved = status == Windows.Storage.Provider.FileUpdateStatus.Complete; } pickerClosed = true; }, false); while (!pickerClosed) { yield return(null); } callback(saved, path); }
// copy paste go brrrr //https://docs.microsoft.com/en-us/windows/uwp/files/quickstart-save-a-file-with-a-picker public async void SaveFile(string name, byte[] bytes) { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as savePicker.FileTypeChoices.Add(Path.GetExtension(name), new List <string>() { Path.GetExtension(name) }); // Default file name if the user does not type one in or select a file to replace savePicker.SuggestedFileName = Path.GetFileNameWithoutExtension(name); Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { // Prevent updates to the remote version of the file until // we finish making changes and call CompleteUpdatesAsync. Windows.Storage.CachedFileManager.DeferUpdates(file); // write to file await Windows.Storage.FileIO.WriteBytesAsync(file, bytes); // Let Windows know that we're finished changing the file so // the other app can update the remote version of the file. // Completing updates may require Windows to ask for user input. Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { // was saved } else { // couldnt be saved } } else { // Operation cancelled } }
private async void ShellMenuItemClick_File_Export(object sender, RoutedEventArgs e) { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; // Dropdown of file types the user can save the file as savePicker.FileTypeChoices.Add("zip-File", new List<string>() { ".zip" }); // Default file name if the user does not type one in or select a file to replace if (InstructionDataProvider.Instruction != null && !string.IsNullOrEmpty(InstructionDataProvider.Instruction.Name)) { savePicker.SuggestedFileName = InstructionDataProvider.Instruction.Name; } StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { // Prevent updates to the remote version of the file until // we finish making changes and call CompleteUpdatesAsync. Windows.Storage.CachedFileManager.DeferUpdates(file); // write to file //var stream = await file.OpenStreamForWriteAsync(); using (Stream zipFileToSave = await file.OpenStreamForWriteAsync()) { zipFileToSave.SetLength(0); await InstructionDataProvider.ExportAsync(ApplicationData.Current.TemporaryFolder.Path, file.DisplayName , zipFileToSave); } // Let Windows know that we're finished changing the file so // the other app can update the remote version of the file. // Completing updates may require Windows to ask for user input. Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { } else { } } else { } }
private async void C_SAVE_PRESET_BUTTON_Click(object sender, RoutedEventArgs e) { Model.TrickerStarPresetSerialize s = new Model.TrickerStarPresetSerialize(); foreach (var item in m_PresetList) { s.PresetCodes.Add(item); } String json_str = Model.JsonHelper.ToJson(s, s.GetType()); var picker = new Windows.Storage.Pickers.FileSavePicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as picker.FileTypeChoices.Add("JSON", new List <string>() { ".json" }); // Default file name if the user does not type one in or select a file to replace picker.SuggestedFileName = "NewDocument"; var t_storagefile = await picker.PickSaveFileAsync(); if (t_storagefile == null) { return; } using (StorageStreamTransaction transaction = await t_storagefile.OpenTransactedWriteAsync()) { using (Windows.Storage.Streams.DataWriter dataWriter = new Windows.Storage.Streams.DataWriter(transaction.Stream)) { dataWriter.WriteString(json_str); transaction.Stream.Size = await dataWriter.StoreAsync(); await transaction.Stream.FlushAsync(); await transaction.CommitAsync(); } } }
private async void SaveAs() { try { var picker = new Windows.Storage.Pickers.FileSavePicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; picker.FileTypeChoices.Add("HDE Project File", new List <string> { ".hdeproj" }); Windows.Storage.StorageFile file = await picker.PickSaveFileAsync(); if (file != null) { Windows.Storage.CachedFileManager.DeferUpdates(file); var obj = GlobalDataService.Instance.CurrentProject; var json = Newtonsoft.Json.JsonConvert.SerializeObject(obj); await Windows.Storage.FileIO.WriteTextAsync(file, json); Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); if (status != Windows.Storage.Provider.FileUpdateStatus.Complete) { await new ContentDialog { Content = "Update File Error", PrimaryButtonText = "Ok" }.ShowAsync(); } GlobalDataService.Instance.CurrentProjectFile = file.Path; GlobalDataService.Instance.OriginHashCode = GlobalDataService.Instance.HashCode; } } catch (Exception e) { await new ContentDialog { Title = "Save Failed", Content = $"{e.Message}", }.ShowAsync(); } }
private async void Save_Click(object sender, RoutedEventArgs e) { var fsp = new Windows.Storage.Pickers.FileSavePicker(); fsp.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; fsp.FileTypeChoices.Add("GIF with embedded ISF", new List <string> { ".gif" }); var file = await fsp.PickSaveFileAsync(); if (null != file) { using (var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)) { await _strokeContainer.SaveAsync(stream); } } }
private async void AppBarButton_Download(object sender, RoutedEventArgs e) { if (ViewModel.CurrentFolder?.Item == null) { var dialog = new MessageDialog("A Letöltéshez először jelentkezz be!"); await dialog.ShowAsync(); return; } else { if (ViewModel.SelectedItem.Item.Folder != null) { var dialog = new MessageDialog("A letöltéshez válassz ki egy fájlt!"); await dialog.ShowAsync(); return; } } MyDriveItem item = new MyDriveItem { DriveItem = ViewModel.SelectedItem.Item }; var picker = new Windows.Storage.Pickers.FileSavePicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Downloads; picker.FileTypeChoices.Add("", new List <string>() { $".{item.Extension}" }); picker.SuggestedFileName = item.DriveItem.Name.Substring(0, item.DriveItem.Name.LastIndexOf(".")); var folder = await picker.PickSaveFileAsync(); if (folder != null) { // read/write jog a mappára StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", folder); await ViewModel.DownloadFile(ViewModel.SelectedItem.Item, folder); } }
public async void SaveEditor() { Windows.Storage.Pickers.FileSavePicker picker = new Windows.Storage.Pickers.FileSavePicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; picker.FileTypeChoices.Add("html", new List <string>() { ".html" }); Windows.Storage.StorageFile file = await picker.PickSaveFileAsync(); if (file == null) { return; } string newContent = mdNote.Pages.MainPage.Editor.generateHtml(); await Windows.Storage.FileIO.WriteTextAsync(file, newContent, Windows.Storage.Streams.UnicodeEncoding.Utf8); }
public static async Task SaveToFile(string value) { Service.ProgressBar.SetProgress(50, true); var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as savePicker.FileTypeChoices.Add("Plain Text", new List <string>() { ".txt" }); // Default file name if the user does not type one in or select a file to replace savePicker.SuggestedFileName = "quanganh9x"; Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { Service.ProgressBar.SetProgress(80, true); // Prevent updates to the remote version of the file until // we finish making changes and call CompleteUpdatesAsync. Windows.Storage.CachedFileManager.DeferUpdates(file); // write to file await Windows.Storage.FileIO.WriteTextAsync(file, value); // Let Windows know that we're finished changing the file so // the other app can update the remote version of the file. // Completing updates may require Windows to ask for user input. Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { await Dialog.Show("success!"); } else { await Dialog.Show("Failed"); } } Service.ProgressBar.Hide(); }
/// <summary> /// Click handler for save graph button. Saves current graph to file. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void SaveGraphBtn_Click(Object sender, RoutedEventArgs e) { Debug.WriteLine("save graph button clicked"); String jsonString = Graph.GraphToJson(this.currentGraph); var savePicker = new Windows.Storage.Pickers.FileSavePicker { SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary }; savePicker.FileTypeChoices.Add("JSON", new List <String>() { ".json" }); savePicker.SuggestedFileName = "New Graph"; Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { Windows.Storage.CachedFileManager.DeferUpdates(file); await Windows.Storage.FileIO.WriteTextAsync(file, jsonString); Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { String message = String.Format("Graph saved to file {0}", file.Path); Debug.WriteLine(message); this.StatusTextBlock.Text = message; } else { String message = String.Format("Graph not saved"); this.StatusTextBlock.Text = message; Debug.WriteLine(message); } } else { Debug.WriteLine("save operation canceled"); this.StatusTextBlock.Text = "save operation canceled."; } }
private async void exportButton_Tapped(object sender, TappedRoutedEventArgs e) { try { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as savePicker.FileTypeChoices.Add("Comma Separated Value (CSV) file", new List <string>() { ".csv" }); // Default file name if the user does not type one in or select a file to replace savePicker.SuggestedFileName = String.Format("Powerwall-{0:yyyy-MM-dd}-{1}.csv", DateTime.Now, periodCombo.SelectedValue); Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { exportButton.Content = "Saving..."; exportButton.IsEnabled = false; if (periodCombo.SelectedIndex <= 1) { await SavePowerInfo(file); } else { await SaveEnergyInfo(file); } exportButton.Content = "Export Data"; exportButton.IsEnabled = true; } } catch (Exception ex) { var md = new MessageDialog("Error while saving data: " + ex.Message); await md.ShowAsync(); } }
private async void IsoSelectButton_ClickAsync(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileSavePicker { SuggestedFileName = MdfFile?.DisplayName ?? "" }; picker.FileTypeChoices.Add("ISO image file", new List <string>() { ".iso" }); StorageFile file = await picker.PickSaveFileAsync(); if (file != null) { IsoFile = file; IsoPathBox.Text = file.Name; } }
private async void Button_Click(object sender, RoutedEventArgs e) { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; //// Dropdown of file types the user can save the file as savePicker.FileTypeChoices.Add("Plain Text", new List <string>() { ".txt" }); //// Default file name if the user does not type one in or select a file to replace savePicker.SuggestedFileName = "New Document"; var file = await savePicker.PickSaveFileAsync(); if (file != null) { FileHandleService.WriteToFile(file, "Hello World"); } }
// 导出成绩 private async void exportScore(object sender, RoutedEventArgs e) { var options = new ExcelExportingOptions(); options.ExcelVersion = ExcelVersion.Excel97to2003; var excelEngine = scoreGrid.ExportToExcel(scoreGrid.View, options); var workBook = excelEngine.Excel.Workbooks[0]; // 选择文件保存的位置和名称 string _xnd = (xnd.SelectedItem as ComboBoxItem).Content.ToString(); string _xq = (xq.SelectedItem as ComboBoxItem).Content.ToString(); var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; savePicker.FileTypeChoices.Add("Excel", new List <string>() { ".xls" }); savePicker.SuggestedFileName = _xnd + "-" + _xq + ".xls"; StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { CachedFileManager.DeferUpdates(file); await workBook.SaveAsAsync(file); Windows.Storage.Provider.FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { await new MessageDialog("成绩导出成功!").ShowAsync(); } else { await new MessageDialog("成绩导出失败!").ShowAsync(); } } else { return; } }
public static async void SaveStringToFile(string s, Dictionary <string, List <string> > filter = null) { try { var picker = new Windows.Storage.Pickers.FileSavePicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; if (filter == null) { filter = new Dictionary <string, List <string> >(); filter.Add("Text File", new List <string>() { ".txt" }); } foreach (var kv in filter) { picker.FileTypeChoices.Add(kv.Key, kv.Value); } Windows.Storage.StorageFile file = await picker.PickSaveFileAsync(); if (file != null) { SaveStringToFile(file, s); //using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync()) //{ // using (DataWriter dataWriter = new DataWriter(transaction.Stream)) // { // dataWriter.WriteString(s); // transaction.Stream.Size = await dataWriter.StoreAsync(); // await transaction.CommitAsync(); // } //} } } catch (Exception ex) { LogSupport.Error(ex); } }
public async void OnClickBtnSaveImage(object sender, RoutedEventArgs e) { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; savePicker.FileTypeChoices.Add("png file", new List <string>() { ".png" }); savePicker.SuggestedFileName = "Default"; var storageFile = await savePicker.PickSaveFileAsync(); if (storageFile != null) { var size = pictureBoxAfter.RenderSize; var renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(pictureBoxAfter, (int)size.Width, (int)size.Height); var displayInformation = DisplayInformation.GetForCurrentView(); using (var stream = await storageFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); encoder.SetPixelData ( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, displayInformation.LogicalDpi, displayInformation.LogicalDpi, (await renderTargetBitmap.GetPixelsAsync()).ToArray() ); await encoder.FlushAsync(); } } return; }
private async void SaveButton_Click(object sender, RoutedEventArgs e) { Windows.Storage.Pickers.FileSavePicker savePicker = new Windows.Storage.Pickers.FileSavePicker { SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary }; // Dropdown of file types the user can save the file as savePicker.FileTypeChoices.Add("Rich Text", new List <string>() { ".rtf" }); // Default file name if the user does not type one in or select a file to replace savePicker.SuggestedFileName = "New Document"; Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { // Prevent updates to the remote version of the file until we // finish making changes and call CompleteUpdatesAsync. Windows.Storage.CachedFileManager.DeferUpdates(file); // write to file Windows.Storage.Streams.IRandomAccessStream randAccStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); MyRichEditBox.Document.SaveToStream(Windows.UI.Text.TextGetOptions.FormatRtf, randAccStream); // Let Windows know that we're finished changing the file so the // other app can update the remote version of the file. Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); if (status != Windows.Storage.Provider.FileUpdateStatus.Complete) { Windows.UI.Popups.MessageDialog errorBox = new Windows.UI.Popups.MessageDialog("File " + file.Name + " couldn't be saved."); await errorBox.ShowAsync(); } } }
// Create private async void ExecuteCreateCommand() { try { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; savePicker.FileTypeChoices.Add("Json", new List<string>() { ".json" }); savePicker.SuggestedFileName = "planets"; Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { Planets = planetRepository.ReloadPlanets(); var json = planetRepository.PlanetsToJson(Planets); await Windows.Storage.FileIO.WriteTextAsync(file, json); } else { Results = "Operation cancelled"; } } catch (Exception x) { Results = x.Message; } }
private async Task<PlotModel> CompareSpeedCarbon(Double step) { var sp = new PerformanceComputing.SpeedParticle(0, 1100000, Environment.ProcessorCount); var plotModel = new PlotModel { Title = "Общая скорость частиц углерода" }; TextBlock item = (TextBlock)ViewSpeed.SelectedItem; var selectedItem = item?.Text; if (selectedItem != null && selectedItem.Equals("Общая")) { Stopwatch st = new Stopwatch(); st.Start(); await sp.DecompositionSpeedCarbonsAsync(Dimensionless.IsChecked != null && (bool)Dimensionless.IsChecked); st.Stop(); var speed = new List<Particle>(sp.CarbonsDecompositionSpeed); Compare(speed); var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" }); // Default file name if the user does not type one in or select a file to replace savePicker.SuggestedFileName = "Распределение скорости карбона"; Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { //StringBuilder text = new StringBuilder(); //foreach (var particle in speed) //{ // text.AppendLine(particle.Vx.ToString()); // text.AppendLine(particle.Vy.ToString()); // text.AppendLine(particle.Vz.ToString()); //} StringBuilder text = new StringBuilder(); text.AppendLine(st.ElapsedMilliseconds.ToString()); text.AppendLine(speed[0].x.ToString()); text.AppendLine(speed[0].y.ToString()); text.AppendLine(speed[0].z.ToString()); await Windows.Storage.FileIO.WriteTextAsync(file, text.ToString()); Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); Windows.Storage.CachedFileManager.DeferUpdates(file); // write to file } var lineSerie = new LinearBarSeries { FillColor = OxyColor.FromArgb(69, 76, 175, 80), StrokeThickness = 1, StrokeColor = OxyColor.FromArgb(255, 76, 175, 80), Title = "Распределение Vx" }; var lineSerie2 = new LinearBarSeries { FillColor = OxyColor.FromArgb(69, 255, 255, 0), StrokeThickness = 1, StrokeColor = OxyColor.FromArgb(255, 76, 175, 80), Title = "Распределение Vy" }; var lineSerie3 = new LinearBarSeries { FillColor = OxyColor.FromArgb(69, 72, 118, 255), StrokeThickness = 1, StrokeColor = OxyColor.FromArgb(255, 76, 175, 80), Title = "Распределение Vz" }; Int32 k = 0; for (var i = 0; i < speed.Count; i += 100) { lineSerie.Points.Add(new DataPoint(k++, speed[i].Vx)); } for (var i = 0; i < speed.Count; i += 100) { lineSerie2.Points.Add(new DataPoint(k++, speed[i].Vy)); } for (var i = 0; i < speed.Count; i += 100) { lineSerie3.Points.Add(new DataPoint(k++, speed[i].Vz)); } plotModel.Series.Add(lineSerie); plotModel.Series.Add(lineSerie2); plotModel.Series.Add(lineSerie3); } return plotModel; }
private async void AppBar_Click_Save(object sender, RoutedEventArgs e) { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.FileTypeChoices.Add( new KeyValuePair<string, IList<string>>("Return on investment analysis file", new string[] { ".roi" })); var saveFile = await savePicker.PickSaveFileAsync(); if (saveFile != null) { var currentProject = (Investment_Analysis.Models.ProjectData)App.Current.Resources["ProjectData"]; try { var text = await JsonConvert.SerializeObjectAsync(currentProject); await Windows.Storage.FileIO.WriteTextAsync(saveFile, text); } catch (Exception) { new Windows.UI.Popups.MessageDialog("Could not write the selected file").ShowAsync(); } } }
private void SaveReportButton_Click(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileSavePicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; picker.SuggestedFileName = this.appDataContext.Player1Name.Value + " vs " + this.appDataContext.Player2Name.Value; picker.DefaultFileExtension = ".html"; picker.FileTypeChoices.Add("Web Page", new string[] { ".html" }); string htmlString = this.appDataContext.StrategyReport.Value; picker.PickSaveFileAsync().AsTask().ContinueWith( (storageFile) => { Windows.Storage.StorageFile result = storageFile.Result; Windows.Storage.FileIO.WriteTextAsync(result, htmlString ); }); }
private async void SaveButtonPressed(ChartControlFull sender) { if (sender == chartControlOne) { string dataToSave = chartControlOne.getDataString(); if (dataToSave == null) { ShowErrorDialog("Chart returned no data, please try again later.", "No data to save"); return; } var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" }); // Default file name if the user does not type one in or select a file to replace savePicker.SuggestedFileName = "HeartBeat"; StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { CachedFileManager.DeferUpdates(file); await FileIO.WriteTextAsync(file, dataToSave); Windows.Storage.Provider.FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { ShowErrorDialog("File " + file.Name + " was saved.", "Save to file"); } else { ShowErrorDialog("File " + file.Name + " couldn't be saved.", "Save to file"); } } } }
private async void button2_Click(object sender, RoutedEventArgs e) { if (Dump == null || Dump.Length < 0x10) { MessageDialog msg = new MessageDialog("Can't save the dump !"); await msg.ShowAsync(); return; } MessageDialog msg1 = new MessageDialog("The amiigo dump can be used in the amiigo PC app, automatically generates the write key and checks the uid before writing, use the binary dump only if you know what to do with it, you can also extract the binary dump from an amiigo dump with the PC app", "Save binary dump or amiigo dump ?"); msg1.Commands.Add(new UICommand("Amiigo dump", async (command) => { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; savePicker.FileTypeChoices.Add("binary dump", new List<string>() { ".bin" }); savePicker.SuggestedFileName = "New dump"; Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { Windows.Storage.CachedFileManager.DeferUpdates(file); await Windows.Storage.FileIO.WriteBytesAsync(file, Dump); Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { textBox.Text = "Dump saved !"; } else { textBox.Text = ("File " + file.Name + " couldn't be saved."); } } })); msg1.Commands.Add(new UICommand("Binary dump", async (command) => { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; savePicker.FileTypeChoices.Add("binary dump", new List<string>() { ".bin" }); savePicker.SuggestedFileName = "New dump"; Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { Windows.Storage.CachedFileManager.DeferUpdates(file); byte[] BinDump = new byte[540]; Buffer.BlockCopy(Dump, 17, BinDump, 0, 540); await Windows.Storage.FileIO.WriteBytesAsync(file, BinDump); Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { textBox.Text = "Dump saved !"; } else { textBox.Text = ("File " + file.Name + " couldn't be saved."); } } })); await msg1.ShowAsync(); }
public async System.Threading.Tasks.Task SaveKML(System.Collections.Generic.List<Windows.Devices.Geolocation.BasicGeoposition> mapdata) { #region XML generating XmlDocument xDoc = new XmlDocument(); XmlDeclaration xDec = xDoc.CreateXmlDeclaration("1.0", "utf-8", null); XmlElement kml = xDoc.CreateElement("kml"); kml.SetAttribute("xmlns", @"http://www.opengis.net/kml/2.2"); xDoc.InsertBefore(xDec, xDoc.DocumentElement); xDoc.AppendChild(kml); XmlElement Document = xDoc.CreateElement("Document"); kml.AppendChild(Document); XmlElement name = xDoc.CreateElement("name"); XmlText nameTextMain = xDoc.CreateTextNode(DateTime.Today.ToString()); Document.AppendChild(name); name.AppendChild(nameTextMain); XmlElement description = xDoc.CreateElement("description"); XmlText destext = xDoc.CreateTextNode("Created by JustMeasure app."); Document.AppendChild(description); description.AppendChild(destext); XmlElement Style = xDoc.CreateElement("Style"); Style.SetAttribute("id", "style1"); Document.AppendChild(Style); XmlElement LineStyle = xDoc.CreateElement("LineStyle"); Style.AppendChild(LineStyle); XmlElement LineStyleColor = xDoc.CreateElement("color"); XmlText linestylecolor = xDoc.CreateTextNode("ffffffff"); LineStyle.AppendChild(LineStyleColor); LineStyleColor.AppendChild(linestylecolor); XmlElement LineStyleWidth = xDoc.CreateElement("width"); XmlText linestylewidth = xDoc.CreateTextNode("5"); LineStyle.AppendChild(LineStyleWidth); LineStyleWidth.AppendChild(linestylewidth); XmlElement Polystyle = xDoc.CreateElement("PolyStyle"); Style.AppendChild(Polystyle); XmlElement polystylecolor = xDoc.CreateElement("color"); XmlText polyscolor = xDoc.CreateTextNode("330000ff"); Polystyle.AppendChild(polystylecolor); polystylecolor.AppendChild(polyscolor); XmlElement Placemark = xDoc.CreateElement("Placemark"); Document.AppendChild(Placemark); XmlElement styleUrl = xDoc.CreateElement("styleUrl"); XmlText styleurl = xDoc.CreateTextNode("#style1"); Placemark.AppendChild(styleUrl); styleUrl.AppendChild(styleurl); XmlElement Polygon = xDoc.CreateElement("Polygon"); Placemark.AppendChild(Polygon); XmlElement extrude = xDoc.CreateElement("extrude"); XmlText extrudetext = xDoc.CreateTextNode("1"); Polygon.AppendChild(extrude); extrude.AppendChild(extrudetext); XmlElement altitudeMode = xDoc.CreateElement("altitudeMode"); XmlText relativeToGround = xDoc.CreateTextNode("relativeToGround"); Polygon.AppendChild(altitudeMode); altitudeMode.AppendChild(relativeToGround); XmlElement outerBoundaryIs = xDoc.CreateElement("outerBoundaryIs"); Polygon.AppendChild(outerBoundaryIs); XmlElement LinearRing = xDoc.CreateElement("LinearRing"); outerBoundaryIs.AppendChild(LinearRing); XmlElement coordinates = xDoc.CreateElement("coordinates"); LinearRing.AppendChild(coordinates); for (int i = 0; i < mapdata.Count; i++) { string coord = mapdata[i].Longitude + "," + mapdata[i].Latitude + "\n"; XmlText cord = xDoc.CreateTextNode(coord); coordinates.AppendChild(cord); } #endregion Windows.Storage.Pickers.FileSavePicker savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; savePicker.FileTypeChoices.Add("KML file", new System.Collections.Generic.List<string>() { ".kml" }); savePicker.SuggestedFileName = DateTime.Now.ToString(); Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { Windows.Storage.CachedFileManager.DeferUpdates(file); using (Stream fileStream = await file.OpenStreamForWriteAsync()) { xDoc.Save(fileStream); } Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { SuccessOrNot("SuccessFile"); } else { SuccessOrNot("FailFile"); } } }
private async void Save_Click(object sender, RoutedEventArgs e) { EnableButtons(false); rootPage.NotifyUser("Requesting file to save to", NotifyType.StatusMessage); var picker = new Windows.Storage.Pickers.FileSavePicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary; picker.FileTypeChoices.Add("MP4 files", new List<string>() { ".mp4" }); picker.SuggestedFileName = "TrimmedClip.mp4"; StorageFile file = await picker.PickSaveFileAsync(); if (file != null) { var saveOperation = composition.RenderToFileAsync(file, MediaTrimmingPreference.Precise); saveOperation.Progress = new AsyncOperationProgressHandler<TranscodeFailureReason, double>(async (info, progress) => { await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => { rootPage.NotifyUser(string.Format("Saving file... Progress: {0:F0}%", progress), NotifyType.StatusMessage); })); }); saveOperation.Completed = new AsyncOperationWithProgressCompletedHandler<TranscodeFailureReason, double>(async (info, status) => { await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => { try { var results = info.GetResults(); if (results != TranscodeFailureReason.None || status != AsyncStatus.Completed) { rootPage.NotifyUser("Saving was unsuccessful", NotifyType.ErrorMessage); } else { rootPage.NotifyUser("Trimmed clip saved to file", NotifyType.StatusMessage); } } finally { // Remember to re-enable controls on both success and failure EnableButtons(true); } })); }); } else { rootPage.NotifyUser("User cancelled the file selection", NotifyType.StatusMessage); EnableButtons(true); } }
private async void save_Click(object sender, RoutedEventArgs e) { if (pancakeInk.InkPresenter.StrokeContainer.GetStrokes().Count > 0) { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; savePicker.FileTypeChoices.Add("Gif with embedded ISF", new System.Collections.Generic.List<string> { ".gif" }); Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (null != file) { try { using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { await pancakeInk.InkPresenter.StrokeContainer.SaveAsync(stream); } saved = true; filePath = file.Path; Button btn = sender as Button; if (null == btn) { return; } var parent = VisualTreeHelper.GetParent(btn); if (null != parent) { int count = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < count; i++) { var child = VisualTreeHelper.GetChild(parent, i); if (child != null && child.ToString().Equals(ELLIPSE) && ((Ellipse)child).Width == btn.Width) { ((Ellipse)child).Fill = new SolidColorBrush(Color.FromArgb(255, 88, 91, 144)); break; } } } ResetButtonState(btn); } catch (Exception ex) { #if DEBUG System.Diagnostics.Debug.WriteLine(ex.Message); #endif saved = false; } } } else { } }
//http://stackoverflow.com/questions/6246009/inkcanvas-load-save-operations //https://msdn.microsoft.com/en-us/library/system.windows.controls.inkcanvas(v=vs.110).aspx // https://social.msdn.microsoft.com/Forums/en-US/55bd1f52-78df-45b2-b5cc-5cb6fcfc6ea9/uwp-universal-window-app-run-on-windows-10-inkcanvas-strokes-save-to-jpg-file?forum=wpdevelop /* Saves strokes as a GIF file */ // https://github.com/Microsoft/Windows-universal-samples/blob/93bdfb92b3da76f2e49c959807fc5643bf0940c9/Samples/SimpleInk/cs/Scenario1.xaml.cs async void saveButton_Click(object sender, RoutedEventArgs e) { if (_inkPresenter.StrokeContainer.GetStrokes().Count > 0) { var save = new Windows.Storage.Pickers.FileSavePicker(); save.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; save.FileTypeChoices.Add("Gif with embedded ISF", new System.Collections.Generic.List<String> { ".gif" }); Windows.Storage.StorageFile file = await save.PickSaveFileAsync(); if (null != file) { try { using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream); } } catch (Exception ex) { // Figure out how to notify the user of failure } } } }
private async Task SaveSettings( string authToken ) { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; savePicker.FileTypeChoices.Add( "Plain Text", new List<string>() { ".txt" } ); savePicker.SuggestedFileName = "user"; StorageFile file = await savePicker.PickSaveFileAsync(); if ( file != null ) { // Prevent updates to the remote version of the file until // we finish making changes and call CompleteUpdatesAsync. CachedFileManager.DeferUpdates( file ); // write to file await FileIO.WriteLinesAsync( file, new string[] { authToken } ); // Let Windows know that we're finished changing the file so // the other app can update the remote version of the file. // Completing updates may require Windows to ask for user input. Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync( file ); if ( status == Windows.Storage.Provider.FileUpdateStatus.Complete ) { // Nothing for now } } }
private async void ButtonClickSaveFile(object sender, RoutedEventArgs e) { var canvasContent = SerializeCanvas(); var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.FileTypeChoices.Add( new KeyValuePair<string, IList<string>>("Painter File Format", new string[] { ".paint" }) ); var saveFile = await savePicker.PickSaveFileAsync(); if (saveFile != null) { try { await Windows.Storage.FileIO.WriteTextAsync(saveFile, canvasContent); } catch (Exception) { new Windows.UI.Popups.MessageDialog("Could not write the selected file").ShowAsync(); } } }
public SaveImageCommand() : base(true) { this .Select(e => e.EventArgs.Parameter as MemoryStreamBase64Item) .Where(e => e != null) .Subscribe( async e => { try { var fp = new Windows.Storage.Pickers.FileSavePicker(); fp.FileTypeChoices.Add(SaveImageCommandFileSavePickerPngFiles, new List<string> { ".png" }); fp.DefaultFileExtension = ".png"; var fpicked = await fp.PickSaveFileAsync(); if (fpicked != null) { using (var saveTargetStream = await fpicked.OpenAsync(FileAccessMode.ReadWrite)) { var bitmapSourceStream = await e.GetRandowmAccessStreamAsync(); await ServiceLocator .Instance .Resolve<IImageConvertService>() .ConverterBitmapToTargetStreamAsync(bitmapSourceStream, saveTargetStream); } var msb = new MessageDialog(SaveImageCommandMessageDialogFileSavedNextContent, SaveImageCommandMessageDialogMessageDialogFileSavedNextTitle); var commandOpenFile = new UICommand( SaveImageCommandMessageDialogUICommandOpenFile, async c => { await Launcher.LaunchFileAsync(fpicked); }); // var commandOpenFold = new UICommand( // "Open Folder", //async c => //{ // await Launcher.LaunchFolderAsync( // await fpicked.GetParentAsync(), // new FolderLauncherOptions { DesiredRemainingView = Windows.UI.ViewManagement.ViewSizePreference.UseHalf }); //} // ); var commandCancelIt = new UICommand(SaveImageCommandMessageDialogUICommandLeave); msb.Commands.Add(commandOpenFile); //msb.Commands.Add(commandOpenFold); msb.Commands.Add(commandCancelIt); msb.CancelCommandIndex = 1; msb.DefaultCommandIndex = 0; var selected = await msb.ShowAsync(); } } catch (Exception ex) { } }); }
async void OnSave(object sender, Windows.UI.Xaml.RoutedEventArgs e) { // We don't want to save an empty file if (inkManager.GetStrokes().Count > 0) { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; savePicker.FileTypeChoices.Add("Gif with embedded ISF", new System.Collections.Generic.List<string> { ".gif" }); Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (null != file) { using (var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)) { await inkManager.SaveAsync(stream); rootPage.NotifyUser(inkManager.GetStrokes().Count + " strokes saved!", SDKTemplate.NotifyType.StatusMessage); } } } else { rootPage.NotifyUser("There is no ink to save.", SDKTemplate.NotifyType.ErrorMessage); } }
private async void btnSaveRecognizedText_Click(object sender, RoutedEventArgs e) { Windows.Storage.Pickers.FileSavePicker SavePicker = new Windows.Storage.Pickers.FileSavePicker(); SavePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; SavePicker.DefaultFileExtension = ".txt"; SavePicker.FileTypeChoices.Add("TXT", new string[] { ".txt" }); SavePicker.SuggestedFileName = "untitled"; StorageFile File = await SavePicker.PickSaveFileAsync(); await FileIO.WriteTextAsync(File, txtRecognizedText.Text); }
public async void Button_Save_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; // Dropdown of file types the user can save the file as savePicker.FileTypeChoices.Add("Hypertext Markup Language (HTML)", new List<string>() { ".htm" }); // Default file name if the user does not type one in or select a file to replace savePicker.SuggestedFileName = "index"; Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { // Prevent updates to the remote version of the file until // we finish making changes and call CompleteUpdatesAsync. Windows.Storage.CachedFileManager.DeferUpdates(file); // write to file String editorContents =""; EditCanvas.Document.GetText(0, out editorContents); await Windows.Storage.FileIO.WriteTextAsync(file, editorContents); // Let Windows know that we're finished changing the file so // the other app can update the remote version of the file. // Completing updates may require Windows to ask for user input. Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { } else { this.EditCanvas.Document.SetText(0, "Sorry. Your file " + file.Name + " couldn't be saved."); } } }
async void AppBarButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { // We don't want to save an empty file if (inkCanvas.InkPresenter.StrokeContainer.GetStrokes().Count > 0) { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; savePicker.FileTypeChoices.Add("Gif with embedded ISF", new System.Collections.Generic.List<string> { ".gif" }); Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (null != file) { try { using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream); } ShowMessage(inkCanvas.InkPresenter.StrokeContainer.GetStrokes().Count + " stroke(s) saved!"); } catch (Exception ex) { ShowMessage(ex.Message); } } } else { ShowMessage("Não tem ink para salvar."); } }
public async void SaveFile() { if (Saved) { return; } var fileBuffer = await Response.Content.ReadAsBufferAsync(); int dotIndex = FullName.LastIndexOf('.'); var extName = FullName.Substring(dotIndex); var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; savePicker.FileTypeChoices.Add(new KeyValuePair<string, IList<string>>("file", new List<string> { extName })); savePicker.SuggestedFileName = FullName; LocalStorage = await savePicker.PickSaveFileAsync(); var writeStream = await LocalStorage.OpenTransactedWriteAsync(); await writeStream.Stream.WriteAsync(fileBuffer); await writeStream.CommitAsync(); Saved = true; }
private async void btnSaveWritingAsImage_Click(object sender, RoutedEventArgs e) { if (MyInkManager.GetStrokes().Count > 0) { try { Windows.Storage.Pickers.FileSavePicker SavePicker = new Windows.Storage.Pickers.FileSavePicker(); SavePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; SavePicker.DefaultFileExtension = ".png"; SavePicker.FileTypeChoices.Add("PNG", new string[] { ".png" }); SavePicker.FileTypeChoices.Add("JPG", new string[] { ".jpg" }); StorageFile filesave = await SavePicker.PickSaveFileAsync(); IOutputStream ab = await filesave.OpenAsync(FileAccessMode.ReadWrite); if (ab != null) await MyInkManager.SaveAsync(ab); } catch (Exception) { var MsgDlg = new MessageDialog("Only handwriting can be saved as image.", "Error while saving"); MsgDlg.ShowAsync(); } } else { var MsgDlg = new MessageDialog("Only handwriting can be saved as image.", "Error while saving"); await MsgDlg.ShowAsync(); } }
private async void OnSaveAsync_Click(object sender, RoutedEventArgs e) { string dialogMsg = "Didn't save, canvas is empty"; //Using if statement so we don't save an empty canvas if (inkCanvas.InkPresenter.StrokeContainer.GetStrokes().Count > 0) { dialogMsg = "Your jots have been saved locally"; var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; savePicker.FileTypeChoices.Add("Gif with embedded ISF", new List<string> { ".gif" }); file = await savePicker.PickSaveFileAsync(); if (file != null) { using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream); } } // Recognising the text on the canvas and saving it to the var savedWords GetSaveText(); /* I'm using localSettings from the Settings page I created to get the access token when the user chooses to login to OneNote. Like I said previously, you don't need this - you can do: string token = await LiveIdAuth.GetAuthToken(); */ if (localSettings.Values.Keys.Contains("AccessToken")) { var token = localSettings.Values["AccessToken"]; //Calling the OneNote create page method with the auth token, api route, recognised words on the canvas and the gif file string result = await OneNote.CreatePageWithImage(token.ToString(), _apiRoute, savedWords, file); if (result == "Created") dialogMsg = dialogMsg + " and have been added to OneNote"; } } var dialog = new MessageDialog(dialogMsg); dialog.Commands.Add(new UICommand("OK")); await dialog.ShowAsync(); }
private async void SaveDocument(IPlotModel model, String newDocument) { if (model == null) { var msg = new MessageDialog("График не создан, рассчитайте распределение", "Ошибка сохранения"); await msg.ShowAsync(); return; } var savePicker = new Windows.Storage.Pickers.FileSavePicker { SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary }; savePicker.FileTypeChoices.Add("PDF Document", new List<string>() { ".pdf" }); savePicker.SuggestedFileName = newDocument; StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { CachedFileManager.DeferUpdates(file); var stream = await file.OpenAsync(FileAccessMode.ReadWrite); using (var outputStream = stream.GetOutputStreamAt(0)) { using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream)) { using (var memoryStream = new MemoryStream()) { var pdf = new PdfExporter(); PdfExporter.Export(model, memoryStream, 1000, 400); var bt = memoryStream.ToArray(); dataWriter.WriteBytes(bt); await dataWriter.StoreAsync(); await outputStream.FlushAsync(); } } } var status = await CachedFileManager.CompleteUpdatesAsync(file); if (status == FileUpdateStatus.Complete) { var msg = new MessageDialog("По пути " + file.Path, "Файл сохранен"); await msg.ShowAsync(); } else { var msg = new MessageDialog("Произошла ошибка сохранения"); await msg.ShowAsync(); } } }
private async Task<int> PickFileForWriteAsyncTask(string fileName, string[] filters, int defaultFilterIdx) { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; savePicker.SuggestedFileName = fileName; foreach (var filter in filters) savePicker.FileTypeChoices.Add(filterToKvp(filter)); var file = await savePicker.PickSaveFileAsync(); var fileNum = getFileNum(); Files.Add(new FileEntry(file.Name, file)); var stream = await file.OpenStreamForWriteAsync(); OpenStreams.Add(fileNum, new Tuple<Stream, string>(stream, file.Name)); return fileNum; }
async void OnSaveAsync(object sender, RoutedEventArgs e) { // We don't want to save an empty file if (inkCanvas.InkPresenter.StrokeContainer.GetStrokes().Count > 0) { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; savePicker.FileTypeChoices.Add("Gif with embedded ISF", new System.Collections.Generic.List<string> { ".gif" }); Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (null != file) { try { using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite)) { await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream); } rootPage.NotifyUser(inkCanvas.InkPresenter.StrokeContainer.GetStrokes().Count + " stroke(s) saved!", NotifyType.StatusMessage); } catch (Exception ex) { rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage); } } } else { rootPage.NotifyUser("There is no ink to save.", NotifyType.ErrorMessage); } }
private async void SaveAs() { var savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as savePicker.FileTypeChoices.Add("kerboscript", new List<string>() { ".ks" }); // Default file name if the user does not type one in or select a file to replace savePicker.SuggestedFileName = docShow.FileName; Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); if (file != null) { try { // Prevent updates to the remote version of the file until // we finish making changes and call CompleteUpdatesAsync. Windows.Storage.CachedFileManager.DeferUpdates(file); // write to file string text; OpenCode.Document.GetText(Windows.UI.Text.TextGetOptions.None, out text); docShow.Text = text; await Windows.Storage.FileIO.WriteTextAsync(file, docShow.Text); // Let Windows know that we're finished changing the file so // the other app can update the remote version of the file. // Completing updates may require Windows to ask for user input. Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); } catch (Exception ex) { ContentDialog errorDialog = new ContentDialog() { Title = ex.ToString(),//"File save as error", Content = "Sorry, I can't do that...", PrimaryButtonText = "Ok" }; await errorDialog.ShowAsync(); } } }
private async void SaveFileButtonClick(object sender, RoutedEventArgs e) { var text = ""; foreach (var item in bindingSchedule) { text = text + item.Minutes + " | "; } var savePicker = new Windows.Storage.Pickers.FileSavePicker(); var plainTextFileTypes = new List<string>(new string[] { ".txt" }); savePicker.FileTypeChoices.Add( new KeyValuePair<string, IList<string>>("Plain Text", plainTextFileTypes) ); var saveFile = await savePicker.PickSaveFileAsync(); if (saveFile != null) { await Windows.Storage.FileIO.WriteTextAsync(saveFile, text); await new Windows.UI.Popups.MessageDialog("File Saved!").ShowAsync(); } }