Пример #1
0
        private async void Save(object sender, RoutedEventArgs e)
        {
            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();

            if (file != null)
            {
                CachedFileManager.DeferUpdates(file);
                await FileIO.WriteTextAsync(file, Text.Text);
            }
        }
        public async Task <FileUpdateStatus> SaveInkFileAsync(StorageFile file)
        {
            if (file != null)
            {
                // Prevent updates to the file until updates are finalized with call to CompleteUpdatesAsync.
                CachedFileManager.DeferUpdates(file);

                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await _strokeContainer.SaveAsync(stream);
                }

                // Finalize write so other apps can update file.
                return(await CachedFileManager.CompleteUpdatesAsync(file));
            }

            return(FileUpdateStatus.Failed);
        }
Пример #3
0
        private async void NewFile(object sender, RoutedEventArgs e)
        {
            bool unsnapped = ((ApplicationView.Value != ApplicationViewState.Snapped) || ApplicationView.TryUnsnap());

            if (!unsnapped)
            {
                return;
            }
            FileSavePicker savePicker = new FileSavePicker();

            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            // Dropdown of file types the user can save the file as
            savePicker.FileTypeChoices.Add("Markdown", new List <string>()
            {
                ".md"
            });
            // Default file name if the user does not type one in or select a file to replace
            savePicker.SuggestedFileName = "New Note";

            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.WriteTextAsync(file, "");

                // 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.
                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                if (status == FileUpdateStatus.Complete)
                {
                    LoadFile(file);
                }
                else
                {
                }
            }
            else
            {
            }
        }
        private async void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            var newmusic = new MusicManager();
            // Get the app's local folder to use as the destination folder.
            //StorageFolder localFolder = Windows.Application­Model.Package.Current.Installed­Location;
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            //$"Assets/Images/{drop_category.Text}/";

            // Specify a new name for the copied file.
            string renamedFileName_image = copyfile_image.Name;
            string renamedFileName_song  = copyfile_song.Name;

            // Copy the file to the destination folder and rename it.
            // Replace the existing file if the file already exists.
            StorageFile copiedFile_image = await copyfile_image.CopyAsync(localFolder, renamedFileName_image, NameCollisionOption.ReplaceExisting);

            StorageFile copiedFile_song = await copyfile_song.CopyAsync(localFolder, renamedFileName_song, NameCollisionOption.ReplaceExisting);

            Windows.Storage.Provider.FileUpdateStatus status_image =
                await CachedFileManager.CompleteUpdatesAsync(copiedFile_image);

            Windows.Storage.Provider.FileUpdateStatus status_song =
                await CachedFileManager.CompleteUpdatesAsync(copiedFile_image);

            if (status_image == Windows.Storage.Provider.FileUpdateStatus.Complete)
            {
                msg_image = "File " + copiedFile_image.Name + " was saved.";
            }
            else
            {
                msg_image = "File " + copiedFile_image.Name + " couldn't be saved.";
            }

            if (status_song == Windows.Storage.Provider.FileUpdateStatus.Complete)
            {
                msg_song = "File " + copiedFile_song.Name + " was saved.";
            }
            else
            {
                msg_song = "File " + copiedFile_song.Name + " couldn't be saved.";
            }

            txt_msg.Text = msg_image + " & " + msg_song;
        }
Пример #5
0
        public async static Task <string> SaveUIElementToFile(UIElement element, TileCategory cate)
        {
            try
            {
                string filename = "";
                switch (cate)
                {
                case TileCategory.Small: filename = "smallTile.png"; break;

                case TileCategory.Medium: filename = "mediumTile.png"; break;

                case TileCategory.Wide: filename = "wideTile.png"; break;

                case TileCategory.Large: filename = "largeTile.png"; break;

                default: filename = "largeTile.png"; break;
                }

                var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.GenerateUniqueName);

                CachedFileManager.DeferUpdates(file);
                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var bitmap = new RenderTargetBitmap();
                    await bitmap.RenderAsync(element);

                    var pixels = await bitmap.GetPixelsAsync();

                    var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
                    var encoder    = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, logicalDpi, logicalDpi, pixels.ToArray());

                    await encoder.FlushAsync();
                }
                await CachedFileManager.CompleteUpdatesAsync(file);

                return(file.Name);
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Пример #6
0
        public static async Task <Task> SaveToFile <T>(ObservableCollection <T> collection)
        {
            try
            {
                file = await storageFolder.GetFileAsync(FileName);
            }
            catch (FileNotFoundException)
            {
                file = await storageFolder.CreateFileAsync(FileName);
            }

            try
            {
                tmpFile = await storageFolder2.GetFileAsync(FileName2);
            }
            catch (FileNotFoundException)
            {
                tmpFile = await storageFolder2.CreateFileAsync(FileName2);
            }

            CachedFileManager.DeferUpdates(file);
            CachedFileManager.DeferUpdates(tmpFile);

            switch (typeof(T).Name)
            {
            case "OrderModel":
                HandleOrderModel(collection as ObservableCollection <OrderModel>);
                break;

            case "MerchandiseModel":
                HandleMerchandiseModel(collection as ObservableCollection <MerchandiseModel>);
                break;

            case "CustomerModel":
                HandleCustomerModel(collection as ObservableCollection <CustomerModel>);
                break;

            case "SupplierModel":
                HandleSupplierModel(collection as ObservableCollection <SupplierModel>);
                break;
            }

            return(GetFileSaveStatus());
        }
Пример #7
0
        private async void SaveFileButton_Click(object sender, RoutedEventArgs e)
        {
            // Clear previous returned file name, if it exists, between iterations of this scenario
            rootPage.ResetScenarioOutput(OutputTextBlock);

            if (rootPage.EnsureUnsnapped())
            {
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation = 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";
                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.WriteTextAsync(file, file.Name);

                    // 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.
                    FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                    if (status == FileUpdateStatus.Complete)
                    {
                        OutputTextBlock.Text = "File " + file.Name + " was saved.";
                    }
                    else
                    {
                        OutputTextBlock.Text = "File " + file.Name + " couldn't be saved.";
                    }
                }
                else
                {
                    OutputTextBlock.Text = "Operation cancelled.";
                }
            }
        }
Пример #8
0
        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.";
                }
            }
        }
Пример #9
0
        private async void QuickSave_Click(object sender, RoutedEventArgs e)
        {
            if (tapped == null)
            {
                return;
            }
            var            i      = tapped;
            FileSavePicker picker = new FileSavePicker();

            picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            picker.FileTypeChoices.Add(GetResourceString("ImageFilePlain"), new List <string>()
            {
                ".png"
            });
            picker.SuggestedFileName = i.Title;
            var file = await picker.PickSaveFileAsync();

            if (file != null)
            {
                CachedFileManager.DeferUpdates(file);
                var res = await new PixivAppAPI(Data.OverAll.GlobalBaseAPI)
                          .IllustDetail(i.ItemId.ToString());
                var illust = Data.IllustDetail.FromJsonValue(res);
                using (var imgstream = await Data.OverAll.DownloadImage(illust.OriginalUrls[0]))
                {
                    using (var filestream = await file.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        await imgstream.CopyToAsync(filestream.AsStream());
                    }
                }
                var updateStatus = await CachedFileManager.CompleteUpdatesAsync(file);

                if (updateStatus == FileUpdateStatus.Complete)
                {
                    await(((((Frame.Parent as Grid).Parent as Page).Parent as Frame).Parent as Grid)?.Parent as MainPage)?.
                    ShowTip(string.Format(GetResourceString("WorkSavedPlain"), i.Title));
                }
                else
                {
                    await(((((Frame.Parent as Grid).Parent as Page).Parent as Frame).Parent as Grid)?.Parent as MainPage)?.
                    ShowTip(string.Format(GetResourceString("WorkSaveFailedPlain"), i.Title));
                }
            }
        }
Пример #10
0
        private async Task OnSaveAs()
        {
            var file = await GetSaveProjectPathAsync(_context.Editor.Project.Name);

            if (file != null)
            {
                CachedFileManager.DeferUpdates(file);

                using (var stream = await file.OpenStreamForWriteAsync())
                {
                    await Task.Run(() =>
                    {
                        T2d.Project.Save(stream, _context.Editor.Project, _context.Serializer);
                    });
                }

                await CachedFileManager.CompleteUpdatesAsync(file);
            }
        }
Пример #11
0
        private async void ExportProfileClicked(object sender, RoutedEventArgs e)
        {
            AnalysisSampleDataItem selectedItem = RecordGrid.SelectedItem as AnalysisSampleDataItem;

            FileSavePicker savePicker = new FileSavePicker();

            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            // Dropdown of file types the user can save the file as

            savePicker.FileTypeChoices.Add("Tabular Data", new List <string>()
            {
                ".csv"
            });
            // Default file name if the user does not type one in or select a file to replace

            savePicker.SuggestedFileName = selectedItem.Name;

            StorageFile file = await savePicker.PickSaveFileAsync();


            if (file != null && selectedItem != null)
            {
                CachedFileManager.DeferUpdates(file);

                // write to file
                AnalysisExportProgressRing.IsActive   = true;
                AnalysisExportProgressRing.Visibility = Windows.UI.Xaml.Visibility.Visible;
                await FileIO.WriteTextAsync(file, ExtraModules.getFileDataForAnalysisItem(selectedItem));

                AnalysisExportProgressRing.IsActive   = false;
                AnalysisExportProgressRing.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                if (status == FileUpdateStatus.Complete)
                {
                    Debug.WriteLine("File " + file.Name + " was saved.");
                }
                else
                {
                    Debug.WriteLine("File " + file.Name + " couldn't be saved.");
                }
            }
        }
Пример #12
0
        private async void SaveShitBtn_Click(object sender, RoutedEventArgs e)
        {
            //код ниже можно пихнуть в try-catch но делять я это не буду ибо х#й потом это отладишь

            //диалоговое окно сохранения файла
            FileSavePicker savePicker = new FileSavePicker();

            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            savePicker.FileTypeChoices.Add("Rich Text", new List <string>()
            {
                ".rtf"
            });
            savePicker.SuggestedFileName = "New Shit";//дефолтное имя

            StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)//не даст словить NRE и похожую дичь
            {
                CachedFileManager.DeferUpdates(file);
                using (Windows.Storage.Streams.IRandomAccessStream randomAccessStream =
                           await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
                {
                    ShitEditor.Document.SaveToStream(Windows.UI.Text.TextGetOptions.FormatRtf, randomAccessStream);
                }

                //сообщаем винде что редактирование говна произведено
                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                if (status != FileUpdateStatus.Complete)
                {
                    //на случай если произошла х#йня
                    Windows.UI.Popups.MessageDialog errorBox =
                        new Windows.UI.Popups.MessageDialog("Press F to " + file.Name);
                    await errorBox.ShowAsync();
                }
            }
            else //если дичь таки произошла
            {
                Windows.UI.Popups.MessageDialog errorBox =
                    new Windows.UI.Popups.MessageDialog("Начальника, всё сломався!");
                await errorBox.ShowAsync();
            }
        }
Пример #13
0
        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);
            }

            // start a new loging session
            rootPage.loggingSessionView = new FileLoggingSession("SensorExplorerLogViewNew");
            rootPage.loggingSessionView.AddLoggingChannel(rootPage.loggingChannelView);
        }
        /// <summary>
        /// 直接保存文件,传入之前合成写入的文件名称.
        /// 如果保存成功返回true,保存失败则返回false.[前台UI线程方法]
        /// </summary>
        /// <param name="fileName">临时文件名,默认为"test.gif"</param>
        /// <returns>如果保存成功返回true,保存失败则返回false.</returns>
        public async static Task <bool> SaveSynthesisGif(string fileName = "test.gif")
        {
            bool ok = false;

            //进行保存
            try
            {
                StorageFolder storageFolder = await ControlLibrary.CacheManagement.CacheManagement.Instance.GetImageFolder();

                StorageFile storageFile = await storageFolder.GetFileAsync(fileName);

                if (storageFile != null)
                {
                    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)
                        {
                            ok = true;
                        }
                    }
                }
            }
            catch
            {
                ok = false;
            }
            return(ok);
        }
Пример #15
0
        private async Task SaveData()
        {
            StorageFile file = await FilePickerAdapters.ShowSaveFilePicker("ColorData", ".json", new Tuple <string, IList <string> >[] { new Tuple <string, IList <string> >("JSON", new List <string>()
                {
                    ".json"
                }) }, null, Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary, true, true);

            if (file == null)
            {
                return;
            }
            CachedFileManager.DeferUpdates(file);

            Preset savePreset = new Preset(file.Path, file.DisplayName, _paletteModel);
            var    saveData   = Preset.Serialize(savePreset);
            var    saveString = saveData.Stringify();

            await FileIO.WriteTextAsync(file, saveString);

            FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

            if (status == FileUpdateStatus.Complete)
            {
                _paletteModel.AddOrReplacePreset(savePreset);
                _paletteModel.ApplyPreset(savePreset);
            }
            else
            {
                if (file == null || file.Path == null)
                {
                    return;
                }
                var           message          = string.Format(_stringProvider.GetString("ControlPaletteSaveError"), file.Path);
                ContentDialog saveFailedDialog = new ContentDialog()
                {
                    CloseButtonText = _stringProvider.GetString("ControlPaletteErrorOkButtonCaption"),
                    Title           = _stringProvider.GetString("ControlPaletteSaveErrorTitle"),
                    Content         = message
                };
                _ = saveFailedDialog.ShowAsync();
                return;
            }
        }
Пример #16
0
        private async Task WriteToFile()
        {
            var file = await GetFile("plain/text", ".txt");

            UpdateFileStatus(file);
            FileUpdateStatus.Text = "Deferring";
            CachedFileManager.DeferUpdates(file);

            var stream = await file.OpenStreamForWriteAsync();

            using (var writer = new StreamWriter(stream))
            {
                writer.Write("Hi, this is the content of the file.");
            }

            var status = await CachedFileManager.CompleteUpdatesAsync(file);

            FileUpdateStatus.Text = status.ToString();
        }
Пример #17
0
        //序列化
        public async void SerializeFile(ReaderManage reader)
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(ReaderManage));
            var savePicker = new FileSavePicker();

            savePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
            // Dropdown of file types the user can save the file as
            savePicker.FileTypeChoices.Add("exReader文件", new List <string>()
            {
                ".xread"
            });
            // Default file name if the user does not type one in or select a file to replace
            savePicker.SuggestedFileName = "xPassage";
            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
                var stream = await file.OpenStreamForWriteAsync();

                Debug.WriteLine("write stream: " + stream.ToString());
                serializer.WriteObject(stream, reader);

                Windows.Storage.Provider.FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                ShowToastNotification("exReader提示", "成功导出工程文件!");
                if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
                {
                    //.textBlock.Text = "File " + file.Name + " was saved.";
                }
                else
                {
                    //this.textBlock.Text = "File " + file.Name + " couldn't be saved.";
                }
            }
            else
            {
                //this.textBlock.Text = "Operation cancelled.";
            }
        }
Пример #18
0
        private async Task <StorageFile> SaveTemporaryPhotoAsync(FilteredPhotoModel photo)
        {
            var filename = Application.Current.Resources["PhotoSaveTemporaryFilename"] as string;
            var folder   = ApplicationData.Current.TemporaryFolder;

            if (filename != null)
            {
                var task = folder.CreateFileAsync(filename, Windows.Storage.CreationCollisionOption.ReplaceExisting).AsTask();
                task.Wait();
                var file = task.Result;

                CachedFileManager.DeferUpdates(file);

                using (var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
                    using (var photoStream = await photo.GetFilteredPhotoAsync())
                        using (var reader = new DataReader(photoStream))
                            using (var writer = new DataWriter(fileStream))
                            {
                                await reader.LoadAsync((uint)photoStream.Size);

                                var buffer = reader.ReadBuffer((uint)photoStream.Size);

                                writer.WriteBuffer(buffer);
                                await writer.StoreAsync();

                                await writer.FlushAsync();
                            }

                var status = await CachedFileManager.CompleteUpdatesAsync(file);

                if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
                {
                    return(file);
                }
                else
                {
                    return(null);
                }
            }

            return(null);
        }
Пример #19
0
        private async void DownloadDBButton_Click(object sender, RoutedEventArgs e)
        {
            var download = await Data.DownloadDB();

            if (download == null)
            {
                return;
            }

            var savePicker = new FileSavePicker();

            savePicker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
            savePicker.FileTypeChoices.Add(download.Type + " File", new List <string>()
            {
                download.Type
            });
            savePicker.SuggestedFileName = download.Name;

            StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                CachedFileManager.DeferUpdates(file);
                await FileIO.WriteBytesAsync(file, download.Data);

                FileUpdateStatus status =
                    await CachedFileManager.CompleteUpdatesAsync(file);

                if (status == FileUpdateStatus.Complete)
                {
                    //save
                }
                else
                {
                    // not saved
                }
            }
            else
            {
                //cancel
            }
        }
Пример #20
0
        async private void saveFile_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                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();

                if (file != null)
                {
                    CachedFileManager.DeferUpdates(file);
                    await FileIO.WriteTextAsync(file, fileText.Text);

                    FileUpdateStatus updateStatus = await CachedFileManager.CompleteUpdatesAsync(file);

                    if (updateStatus == FileUpdateStatus.Complete)
                    {
                        status.Log(string.Format(CultureInfo.CurrentCulture,
                                                 LocalizableStrings.FILE_PICKER_SAVE_SUCCESS, file.Name));
                    }
                    else
                    {
                        status.Log(string.Format(CultureInfo.CurrentCulture,
                                                 LocalizableStrings.FILE_PICKER_SAVE_FAIL, file.Name));
                    }
                }
                else
                {
                    status.Log(string.Format(CultureInfo.CurrentCulture,
                                             LocalizableStrings.FILE_PICKER_NO_SELECTION));
                }
            }
            catch (Exception ex)
            {
                status.Log(ex.Message);
            }
        }
Пример #21
0
        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");
                }
                //}
            }
        }
Пример #22
0
        /// <summary>
        ///     https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh700391.aspx
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            if (((ApplicationView.Value != ApplicationViewState.Snapped) ||
                 ApplicationView.TryUnsnap()))
            {
                var savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation = 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";

                var 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
                    var randAccStream =
                        await file.OpenAsync(FileAccessMode.ReadWrite);

                    inputText.Document.SaveToStream(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.
                    var status = await CachedFileManager.CompleteUpdatesAsync(file);

                    if (status != FileUpdateStatus.Complete)
                    {
                        var errorBox =
                            new MessageDialog("File " + file.Name + " couldn't be saved.");
                        await errorBox.ShowAsync();
                    }
                }
            }
        }
Пример #23
0
        private async void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            FileSavePicker savePicker = new FileSavePicker
            {
                SuggestedStartLocation = 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";

            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
                using (Windows.Storage.Streams.IRandomAccessStream randAccStream =
                           await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
                {
                    editor.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.
                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                if (status != FileUpdateStatus.Complete)
                {
                    Windows.UI.Popups.MessageDialog errorBox =
                        new Windows.UI.Popups.MessageDialog("File " + file.Name + " couldn't be saved.");
                    await errorBox.ShowAsync();
                }
            }
        }
Пример #24
0
        public async Task SaveFileWord(byte[] fileData)
        {
            var savePicker = new FileSavePicker();

            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            savePicker.FileTypeChoices.Add("Документ", new List <string>()
            {
                ".docx"
            });

            StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                CachedFileManager.DeferUpdates(file);
                await FileIO.WriteBytesAsync(file, fileData);

                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
            }
        }
Пример #25
0
        /// <summary>
        ///     Saves the text to a file.
        /// </summary>
        /// <param name="text">The text.</param>
        public static async void SaveText(string text)
        {
            var fileSavePicker = new FileSavePicker {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
                SuggestedFileName      = "New Document"
            };

            fileSavePicker.FileTypeChoices.Add("Plain Text", new List <string> {
                ".txt"
            });
            var saveFile = await fileSavePicker.PickSaveFileAsync();

            if (saveFile != null)
            {
                CachedFileManager.DeferUpdates(saveFile);
                await FileIO.WriteTextAsync(saveFile, text);

                await CachedFileManager.CompleteUpdatesAsync(saveFile);
            }
        }
Пример #26
0
        private async void ExportButton_Click(object sender, RoutedEventArgs e)
        {
            var fileSavePicker = new FileSavePicker
            {
                SuggestedFileName = "Captive Portal Assistant Profiles",
                FileTypeChoices   =
                {
                    { "JSON", new List <string> {
                          ".json"
                      } }
                }
            };
            var storageFile = await fileSavePicker.PickSaveFileAsync();

            if (storageFile == null)
            {
                return;
            }
            CachedFileManager.DeferUpdates(storageFile);
            var isSuccess = true;

            try
            {
                await ProfilesService.Instance.Export(storageFile);
            }
            catch (Exception)
            {
                isSuccess = false;
            }
            var fileUpdateStatus = await CachedFileManager.CompleteUpdatesAsync(storageFile);

            var contentDialog = new ContentDialog
            {
                Title   = "Export profiles",
                Content = isSuccess && fileUpdateStatus == FileUpdateStatus.Complete
                    ? "Exported successfully."
                    : "Export failed, please try again.",
                CloseButtonText = "Ok"
            };
            await contentDialog.ShowAsync();
        }
Пример #27
0
        // 导出成绩
        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 async Task <bool> Finish()
        {
            var ok = false;

            Flush();
            if (_writeVBRHeader)
            {
                _fs.Seek(0, SeekOrigin.Begin);
                WriteVBRHeader(false);
            }
            //完成转换写入文件
            if (_fs != null && _fs.Length > 0)
            {
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
                savePicker.FileTypeChoices.Add("音乐类型", new List <string>()
                {
                    ".mp3"
                });

                savePicker.SuggestedFileName = _name;// +".mp3";
                StorageFile file = await savePicker.PickSaveFileAsync();

                if (file != null)
                {
                    CachedFileManager.DeferUpdates(file);
                    byte[] bytes = _fs.ToArray();
                    await FileIO.WriteBytesAsync(file, bytes);

                    FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                    if (status == FileUpdateStatus.Complete)
                    {
                        ok = true;
                    }
                }
            }
            //_fs.Close();
            _fs.Dispose();
            return(ok);
        }
Пример #29
0
        public async void Savefile2(string jpguri)//不调用自愿选择器
        {
            //Savefile();
            //UWP应用在任何情况下都不支持直接使用Path,也就是文本路径,必须使用StorageFolder。FolderPicker返回的就是一个StorageFolder,你需要使用这个,否则就只能使用下面链接中的位置了
            try
            {
                string fileuri = localsettings.Values["_Fileuri"].ToString();

                StorageFolder storagefolder = await StorageFolder.GetFolderFromPathAsync(fileuri);

                storagefile = await storagefolder.CreateFileAsync(imgname + "ID" + imgid + ".jpg", CreationCollisionOption.ReplaceExisting);

                if (storagefile != null)
                {
                    CachedFileManager.DeferUpdates(storagefile);
                    await  showtast();

                    string Filename     = imgname + imgid;
                    string _transferUri = jpguri;
                    Uri    transferUri;
                    try
                    {
                        transferUri = new Uri(Uri.EscapeUriString(_transferUri), UriKind.RelativeOrAbsolute);
                    }
                    catch
                    {
                        return;
                    }

                    BackgroundDownloader backgrounddownloader = new BackgroundDownloader();//后台下载
                    DownloadOperation    downloader           = backgrounddownloader.CreateDownload(transferUri, storagefile);
                    await downloader.StartAsync();
                }
                //HttpClient httpclient = new HttpClient();
                //HttpResponseMessage httpResponseMessage = await httpclient.GetAsync(new Uri(jpguri));
            }
            catch (Exception ex)
            {
                await new MessageDialog(ex.ToString()).ShowAsync();
            }
        }
Пример #30
0
        private async void btnMySavePicker_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            FileSavePicker savePicker = new FileSavePicker();

            savePicker.FileTypeChoices.Add("文本", new List <string>()
            {
                ".txt"
            });

            // 弹出文件保存窗口
            StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                /*
                 * 运行到此,只是在目标地址创建了一个没有任何内容的空白文件而已,接下来开始向文件写入内容
                 */

                // 告诉 Windows ,从此时开始要防止其它程序更新指定的文件
                CachedFileManager.DeferUpdates(file);

                // 将指定的内容保存到指定的文件
                string textContent = "I am webabcd";
                await FileIO.WriteTextAsync(file, textContent);

                // 告诉 Windows ,从此时开始允许其它程序更新指定的文件
                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                if (status == FileUpdateStatus.Complete)
                {
                    lblMsg.Text = "文件 " + file.Name + " 保存成功";
                }

                lblMsg.Text += Environment.NewLine;
                lblMsg.Text += "FileUpdateStatus: " + status.ToString();
            }
            else
            {
                lblMsg.Text = "取消了";
            }
        }