PickSaveFileAsync() 공개 메소드

public PickSaveFileAsync ( ) : IAsyncOperation
리턴 IAsyncOperation
        private async void ButtonCamera_Click(object sender, RoutedEventArgs e)
        {
            CameraCaptureUI captureUI = new CameraCaptureUI();
            captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;
            captureUI.PhotoSettings.CroppedSizeInPixels = new Size(600, 600);

            StorageFile photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);

            if (photo != null)
            {
                BitmapImage bmp = new BitmapImage();
                IRandomAccessStream stream = await photo.
                                                   OpenAsync(FileAccessMode.Read);
                bmp.SetSource(stream);
                BBQImage.Source = bmp;

                FileSavePicker savePicker = new FileSavePicker();
                savePicker.FileTypeChoices.Add
                                      ("jpeg image", new List<string>() { ".jpeg" });

                savePicker.SuggestedFileName = "New picture";

                StorageFile savedFile = await savePicker.PickSaveFileAsync();

                (this.DataContext as BBQRecipeViewModel).imageSource = savedFile.Path;

                if (savedFile != null)
                {
                    await photo.MoveAndReplaceAsync(savedFile);
                }
            }
        }
예제 #2
0
        async void SaveTheForest()
        {
            var displayInformation = DisplayInformation.GetForCurrentView();
            var imageSize = new Size(ACTWIDTH, ACTHEIGHT);
            canvasOfAvaga.Measure(imageSize);
            canvasOfAvaga.UpdateLayout();
            canvasOfAvaga.Arrange(new Rect(0, 0, imageSize.Width, imageSize.Height));

            var renderTargetBitmap = new RenderTargetBitmap();
            await renderTargetBitmap.RenderAsync(canvasOfAvaga, Convert.ToInt32(imageSize.Width), Convert.ToInt32(imageSize.Height));
            //await renderTargetBitmap.RenderAsync(canvasOfAvaga, Convert.ToInt32(ACTWIDTH), Convert.ToInt32(ACTHEIGHT));

            var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
            var picker = new FileSavePicker();
            picker.FileTypeChoices.Add(".jpg",new[] {".jpg"});
            var file = picker.PickSaveFileAsync();
            //var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("D:\\Screen.jpg", CreationCollisionOption.ReplaceExisting);
            using (var fileStream = await (await picker.PickSaveFileAsync()).OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, fileStream);

                encoder.SetPixelData(
                        BitmapPixelFormat.Bgra8,
                        BitmapAlphaMode.Ignore,
                        (uint)renderTargetBitmap.PixelWidth,
                        (uint)renderTargetBitmap.PixelHeight,
                        displayInformation.LogicalDpi,
                        displayInformation.LogicalDpi,
                        pixelBuffer.ToArray());

                await encoder.FlushAsync();
            }
        }
예제 #3
0
 /// <summary>
 /// 保存文件
 /// </summary>
 /// <param name="url"></param>
 /// <param name="savedPath"></param>
 /// <returns></returns>
 public static async Task<bool> Save(string url, string savedPath = null)
 {
     var uri = new Uri(url);
     var bytes = await uri.GetBytesFromUri();
     var extension = IsGif(bytes) ? ".gif" : ".jpg";
     string text = DateTime.Now.Ticks + extension;
     StorageFile storageFile = null;
     if (savedPath == null)
     {
         FileSavePicker fileSavePicker = new FileSavePicker();
         fileSavePicker.FileTypeChoices.Add("image", new List<string> { extension });
         fileSavePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
         fileSavePicker.SuggestedFileName = text;
         storageFile = await fileSavePicker.PickSaveFileAsync();
     }
     else
     {
         StorageFolder storageFolder = await KnownFolders.PicturesLibrary.CreateFolderAsync(savedPath, CreationCollisionOption.OpenIfExists);
         storageFile = await storageFolder.CreateFileAsync(text, CreationCollisionOption.ReplaceExisting);
     }
     if (storageFile == null)
     {
         return false;
     }
     await FileIO.WriteBytesAsync(storageFile, bytes);
     return true;
 }
예제 #4
0
        private async Task SaveBitmap(RenderTargetBitmap rtb, SoftwareBitmap swBmp)
        {
            FileSavePicker filePicker = new Windows.Storage.Pickers.FileSavePicker();

            filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            filePicker.FileTypeChoices.Add("JPG file", new List <string>()
            {
                ".jpg"
            });
            StorageFile file = await filePicker.PickSaveFileAsync();

            if (file != null)
            {
                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    IBuffer buffer = await rtb.GetPixelsAsync();

                    Windows.Storage.Streams.DataReader dataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer);
                    byte[] generatedImage = new byte[buffer.Length];
                    dataReader.ReadBytes(generatedImage);
                    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream);

                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)rtb.PixelWidth, (uint)rtb.PixelHeight, swBmp.DpiX, swBmp.DpiY, generatedImage);
                    await encoder.FlushAsync();
                }
            }
        }
예제 #5
0
		private async Task SaveLogFile(string sourcePath, string suggestedFilename)
		{
			var picker = new FileSavePicker
			{
				SuggestedFileName = suggestedFilename,
				SuggestedStartLocation = PickerLocationId.DocumentsLibrary
			};
			picker.FileTypeChoices.Add("Plain Text", new[] { ".txt" });

			var file = await picker.PickSaveFileAsync();

			if (file != null)
			{
				byte[] bytes;

				if (!File.Exists(sourcePath))
				{
					bytes = new byte[0];
				}
				else
				{
					// This way, we can read the file at the same time as we are logging to it.
					using (var fs = File.Open(sourcePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite))
					using (var reader = new BinaryReader(fs))
						bytes = reader.ReadBytesAndVerify((int)fs.Length);
				}

				await FileIO.WriteBytesAsync(file, bytes);
			}
		}
예제 #6
0
        public static async Task<FileUpdateStatus> SaveToPngImage(this WriteableBitmap bitmap, PickerLocationId location, string fileName)
        {
            var savePicker = new FileSavePicker
            {
                SuggestedStartLocation = location
            };
            savePicker.FileTypeChoices.Add("Png Image", new[] { ".png" });
            savePicker.SuggestedFileName = fileName;
            StorageFile sFile = await savePicker.PickSaveFileAsync();
            if (sFile != null)
            {
                CachedFileManager.DeferUpdates(sFile);

                using (var fileStream = await sFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);
                    Stream pixelStream = bitmap.PixelBuffer.AsStream();
                    byte[] pixels = new byte[pixelStream.Length];
                    await pixelStream.ReadAsync(pixels, 0, pixels.Length);
                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                              (uint)bitmap.PixelWidth,
                              (uint)bitmap.PixelHeight,
                              96.0,
                              96.0,
                              pixels);
                    await encoder.FlushAsync();
                }

                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(sFile);
                return status;
            }
            return FileUpdateStatus.Failed;
        }
        private async void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            FileSavePicker 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";

            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();
                }
            }
        }
예제 #8
0
        public static async Task <bool> ExportStorageFileToLocalFolder(StorageFile tosaved, String suggestFileName)
        {
            try
            {
                if (tosaved != null)
                {
                    var picker = new Windows.Storage.Pickers.FileSavePicker();
                    picker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
                    picker.SuggestedFileName      = suggestFileName;

                    var filedb = new[] { ".db" };
                    picker.FileTypeChoices.Add("DB", filedb);


                    var file = await picker.PickSaveFileAsync();

                    if (file != null)
                    {
                        await tosaved.CopyAndReplaceAsync(file);

                        return(true);
                    }
                }
                return(false);
            }

            catch (Exception)
            {
                return(false);
            }
        }
예제 #9
0
        private async void saveAdventure_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 create
            savePicker.FileTypeChoices.Add("Plain Text", new List <string>()
            {
                ".json", ".agf"
            });
            savePicker.SuggestedFileName = "newAdv.json";
            Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                Windows.Storage.CachedFileManager.DeferUpdates(file);
                await Windows.Storage.FileIO.WriteTextAsync(file, AdventureGame.saveToString(game.data));

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

                if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
                {
                    //success
                }
                else
                {
                    await new MessageDialog("Error Saving Adventure Game!", "Error").ShowAsync();
                    return;
                }
            }
        }
예제 #10
0
    public async Task <string> SaveAsync(byte[] fileData, DataFileDialogModel dataFileDialog)
    {
        var savePicker = new Windows.Storage.Pickers.FileSavePicker();

        savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
        savePicker.FileTypeChoices.Add(dataFileDialog.TypeName, new List <string>()
        {
            dataFileDialog.FileType
        });
        savePicker.SuggestedFileName = dataFileDialog.DefaultFileName;
        Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();

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

            FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

            if (status == FileUpdateStatus.Complete)
            {
                return($"Файл {file.Name} сохранен");
            }
            else
            {
                return($"Ошибка сохранения Файла {file.Name}");
            }
        }
        else
        {
            return($"Сохранение файла отменено");
        }
    }
        private async void save_Video(object sender, RoutedEventArgs e)
        {
            // Adding try catch block in case of occurence of an exception
            try
            {
                // Creating object of FileSavePicker and adding few values to the properties of the object.
                FileSavePicker fs = new FileSavePicker();
                fs.FileTypeChoices.Add("Video", new List<string>() { ".mp4",".3gp" });
                fs.DefaultFileExtension = ".mp4";
                fs.SuggestedFileName = "Video" + DateTime.Today.ToString();
                fs.SuggestedStartLocation = PickerLocationId.VideosLibrary;

                // Using storagefile object defined earlier in above method to save the file using filesavepicker.
                fs.SuggestedSaveFile = sf;

                // Saving the file
                var s = await fs.PickSaveFileAsync();
                if (s != null)
                {
                    using (var dataReader = new DataReader(rs.GetInputStreamAt(0)))
                    {
                        await dataReader.LoadAsync((uint)rs.Size);
                        byte[] buffer = new byte[(int)rs.Size];
                        dataReader.ReadBytes(buffer);
                        await FileIO.WriteBytesAsync(s, buffer);
                    }
                }
            }
            catch (Exception ex)
            {
                var messageDialog = new MessageDialog("Something went wrong.");
                await messageDialog.ShowAsync();
            }
        }
예제 #12
0
        public async Task Save(string filename, string contentType, MemoryStream stream)
        {
            StorageFile storageFile = null;
            FileSavePicker savePicker = new FileSavePicker();
            savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
            savePicker.SuggestedFileName = filename;
            switch (contentType)
            {
                case "application/msexcel":
                    savePicker.FileTypeChoices.Add("Excel Files", new List<string>() { ".xlsx", });
                    break;

                case "application/msword":
                    savePicker.FileTypeChoices.Add("Word Document", new List<string>() { ".docx" });
                    break;

                case "application/pdf":
                    savePicker.FileTypeChoices.Add("Adobe PDF Document", new List<string>() { ".pdf" });
                    break;
                case "application/html":
                    savePicker.FileTypeChoices.Add("HTML Files", new List<string>() { ".html" });
                    break;
            }
            storageFile = await savePicker.PickSaveFileAsync();

            using (Stream outStream = await storageFile.OpenStreamForWriteAsync())
            {
                outStream.Write(stream.ToArray(), 0, (int)stream.Length);
            }

            await Windows.System.Launcher.LaunchFileAsync(storageFile);
        }
예제 #13
0
        private async void SaveButtonPressed(object sender, PointerRoutedEventArgs e)
        {
            Windows.Storage.Pickers.FileSavePicker 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("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);

                TxtArea.Document.SaveToStream(Windows.UI.Text.TextGetOptions.FormatRtf, randAccStream);
                Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);
            }
        }
예제 #14
0
        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
       

        private async void sButton_Click(object sender, RoutedEventArgs e)
        {
        //    string x = nameInput.Text;

        //   StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
        //    StorageFile sampleFile = await storageFolder.CreateFileAsync(x);
       
           if (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" });
                savePicker.FileTypeChoices.Add("Java Source File", new List<string>() { ".java" });
                savePicker.FileTypeChoices.Add("C++ Source File", new List<string>() { ".cpp" });
                // Default file name if the user does not type one in or select a file to replace
                savePicker.SuggestedFileName = "New Document";

                IAsyncOperation<StorageFile> asyncOp = savePicker.PickSaveFileAsync();
                StorageFile file = await asyncOp;
                if (this.Frame != null || file != null)
                {
                    this.Frame.Navigate(typeof(CodeEditor));
                }
           }

           


        }
예제 #15
0
        async void btnSave_Click(object sender, RoutedEventArgs e)
        {
            this.AppBars(false);

            try
            {
                var savePicker = new Windows.Storage.Pickers.FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                savePicker.FileTypeChoices.Add("Comma Separated Values", new List <string>()
                {
                    ".csv"
                });

                var file = await savePicker.PickSaveFileAsync();

                if (file != null)
                {
                    var thing = await file.OpenStreamForWriteAsync();

                    using (StreamWriter sw = new StreamWriter(thing.AsOutputStream().AsStreamForWrite()))
                    {
                        CsvSerializer csv = new CsvSerializer();
                        sw.Write(csv.Serialize(pnlStandings.Teams));
                        sw.Write(csv.Serialize(pnlStandings.Games));
                        sw.Write(csv.Serialize(pnlStats.Players));
                    }
                }
            }
            catch
            {
                var dialog = new MessageDialog("Error occured saving file.");
                dialog.ShowAsync();
            }
        }
        private async void SaveFileButton_Click(object sender, RoutedEventArgs e)
        {
            // Clear previous returned file name, if it exists, between iterations of this scenario
            OutputTextBlock.Text = "";

            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.";
            }
        }
예제 #17
0
        public async Task Save(Document document)
        {
            var doc = (LocalDocument)document;
            if (!doc.IsModified)
                return;

            StorageFile file;
            if (doc.File == null)
            {
                var filepicker = new FileSavePicker
                    {
                        DefaultFileExtension = ".md",
                        CommitButtonText = "Save",
                        SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
                    };
                filepicker.FileTypeChoices.Add("Markdown", new List<string> { ".md", ".mdown", ".markdown", ".mkd" });
                file = await filepicker.PickSaveFileAsync();
                doc.File = file;

                string token = StorageApplicationPermissions.FutureAccessList.Add(file, file.Name);
                doc.Token = token;
                _localSettings.Values[file.Name] = token;
            }
            else
                file = doc.File;

            if (file != null)
            {
                doc.Name = file.Name;
                await FileIO.WriteTextAsync(file, doc.Text);
                doc.OriginalText = doc.Text.Trim('\r', '\n');
            }
        }
예제 #18
0
        public static async Task<SaveAllSpecies> Export()
        {

            FileSavePicker exportPicker = new FileSavePicker();

            exportPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            exportPicker.FileTypeChoices.Add("XML", new List<string>() { ".xml" });
            exportPicker.DefaultFileExtension = ".xml";
            exportPicker.SuggestedFileName = "SwarmsSaves";
            exportPicker.CommitButtonText = "Export";
            StorageFile file = await exportPicker.PickSaveFileAsync();
            if (null != file)
            {
                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (Stream outputStream = stream.AsStreamForWrite())
                    {
                        XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
                        xmlWriterSettings.Indent = true;
                        xmlWriterSettings.Encoding = new UTF8Encoding(false);
                        XmlSerializer serializer = new XmlSerializer(typeof(SaveAllSpecies));
                        var game = await SaveHelper.LoadGameFile("AllSaved");
                        using (XmlWriter xmlWriter = XmlWriter.Create(outputStream, xmlWriterSettings))
                        {
                            serializer.Serialize(xmlWriter, game);
                        }
                        await outputStream.FlushAsync();
                        return game;
                    }
                }
            }
            return null;
        }
예제 #19
0
        public static async Task<FileUpdateStatus> SaveStreamToImage(PickerLocationId location, string fileName, Stream stream, int pixelWidth, int pixelHeight)
        {
            var savePicker = new FileSavePicker
            {
                SuggestedStartLocation = location
            };
            savePicker.FileTypeChoices.Add("Png Image", new[] { ".png" });
            savePicker.SuggestedFileName = fileName;
            StorageFile sFile = await savePicker.PickSaveFileAsync();
            if (sFile != null)
            {
                CachedFileManager.DeferUpdates(sFile);

                using (var fileStream = await sFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var localDpi = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().LogicalDpi;

                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);
                    Stream pixelStream = stream;
                    byte[] pixels = new byte[pixelStream.Length];
                    await pixelStream.ReadAsync(pixels, 0, pixels.Length);
                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight,
                              (uint)pixelWidth,
                              (uint)pixelHeight,
                              localDpi,
                              localDpi,
                              pixels);
                    await encoder.FlushAsync();
                }

                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(sFile);
                return status;
            }
            return FileUpdateStatus.Failed;
        }
예제 #20
0
        private async Task Saving(string content)
        {
            var 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("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.
                Windows.Storage.CachedFileManager.DeferUpdates(file);
                // write to file
                await Windows.Storage.FileIO.WriteTextAsync(file, content);

                // 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);
            }
        }
예제 #21
0
        //[保存] ボタンが押された場合の処理
        private async void btnSave_Click(object sender, RoutedEventArgs e)
        {
            //「名前を付けて保存」ダイアログの作成
            var savePicker = new Windows.Storage.Pickers.FileSavePicker();

            savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            savePicker.FileTypeChoices.Add("Png", new List <string> {
                ".png"
            });

            StorageFile file = await savePicker.PickSaveFileAsync();

            if (null != file)
            {
                try
                {
                    using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream);
                    }
                }

                catch (Exception ex)
                {
                    MessageDialog msgDialog = new MessageDialog(ex.Message, "エラー");
                    await msgDialog.ShowAsync();
                }
            }
        }
 /// <summary>
 /// Creates a text file with XAML brushes for a list of named colors.
 /// </summary>
 private async void Save_Executed()
 {
     var savePicker = new FileSavePicker();
     savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
     savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
     savePicker.DefaultFileExtension = ".txt";
     savePicker.SuggestedFileName = "ColorSwatchBrushes";
     StorageFile file = await savePicker.PickSaveFileAsync();
     if (null != file)
     {
         try
         {
             await FileIO.WriteLinesAsync(file, Palette.Select(color => color.AsXamlResource()));
             Toast.ShowInfo("File saved");
         }
         catch (Exception ex)
         {
             Log.Error(ex.Message);
             Toast.ShowError("Oops, something went wrong.");
         }
     }
     else
     {
         Toast.ShowWarning("Operation cancelled.");
     }
 }
예제 #23
0
        public static async Task ExportRecipeBoxAsync(RecipeBox rb = null, RecentRecipeBox rrb = null)
        {
            if (rb == null && rrb == null)
            {
                return;
            }

            string fileContents = JsonConvert.SerializeObject(rb);

            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>()
            {
                ".rcpbx"
            });
            // Default file name if the user does not type one in or select a file to replace
            savePicker.SuggestedFileName = "NewRecipeBox";

            StorageFile newFile = await savePicker.PickSaveFileAsync();

            await FileIO.WriteTextAsync(newFile, fileContents);
        }
예제 #24
0
        public async void SaveFile()
        {
            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";

            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, eText);

                // 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);

                /*
                 * Windows.Storage.StorageFolder storageFolder =
                 * Windows.Storage.ApplicationData.Current.LocalFolder;
                 * Windows.Storage.StorageFile sampleFile =
                 *  await storageFolder.CreateFileAsync(file.Name,
                 *      Windows.Storage.CreationCollisionOption.ReplaceExisting);
                 *
                 * await Windows.Storage.FileIO.WriteTextAsync(sampleFile, eText);
                 */


                if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
                {
                    this.textbox4.Text = "File " + file.Name + " was saved.";
                }
                else
                {
                    this.textbox4.Text = "File " + file.Name + " couldn't be saved.";
                }
            }
            else
            {
                this.textbox4.Text = "Operation cancelled.";
            }
        }
예제 #25
0
        public async void Save()
        {
            try
            {
                if (_file != null)
                {
                    await _fileService.SaveAsync(_file);

                    _toastService.ShowToast(_file, "File  succesfully saved.");
                }
                else
                {
                    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";

                    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, 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.
                        Windows.Storage.Provider.FileUpdateStatus status =
                            await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);

                        if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
                        {
                            await new Windows.UI.Popups.MessageDialog("File " + file.Name + " was saved.").ShowAsync();
                        }
                        else
                        {
                            await new Windows.UI.Popups.MessageDialog("File " + file.Name + " couldn't be saved.").ShowAsync();
                        }
                    }
                    else
                    {
                        await new Windows.UI.Popups.MessageDialog("Operation cancelled.").ShowAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                _toastService.ShowToast(_file, "Save failed. Error : " + ex.Message);
            }
        }
        private async void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) {
            var selected = new List<object>(TileList.SelectedItems);

            var picker = new FileSavePicker();
            picker.SuggestedFileName = $"export_{DateTime.Now.ToString(DateTimeFormatInfo.CurrentInfo.ShortDatePattern)}";
            picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            picker.FileTypeChoices.Add("Tiles file", new List<string>() { ".tiles" });
            var file = await picker.PickSaveFileAsync();
            if (file != null) {
                CachedFileManager.DeferUpdates(file);

                await FileIO.WriteTextAsync(file, "");
                
                using (var stream = await file.OpenStreamForWriteAsync())
                using (var zip = new ZipArchive(stream, ZipArchiveMode.Update)) {

                    while (zip.Entries.Count > 0) {
                        zip.Entries[0].Delete();
                    }

                    using (var metaStream = zip.CreateEntry("tiles.json").Open())
                    using (var writer = new StreamWriter(metaStream)) {
                        var array = new JsonArray();

                        selected.ForEachWithIndex<SecondaryTile>((item, index) => {
                            var objet = new JsonObject();
                            objet.Add("Name", item.DisplayName);
                            objet.Add("Arguments", item.Arguments);
                            objet.Add("TileId", item.TileId);
                            objet.Add("IconNormal", item.VisualElements.ShowNameOnSquare150x150Logo);
                            objet.Add("IconWide", item.VisualElements.ShowNameOnWide310x150Logo);
                            objet.Add("IconBig", item.VisualElements.ShowNameOnSquare310x310Logo);
                            
                            array.Add(objet);

                            if (item.VisualElements.Square150x150Logo.LocalPath != DEFAULT_URI) {
                                var path = ApplicationData.Current.LocalFolder.Path + Uri.UnescapeDataString(item.VisualElements.Square150x150Logo.AbsolutePath.Substring(6));
                                
                                zip.CreateEntryFromFile(path, item.TileId + "/normal");
                            }
                        });
                        writer.WriteLine(array.Stringify());
                        
                    }

                    FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                    if(status == FileUpdateStatus.Complete) {
                        var folder = await file.GetParentAsync();
                        await new MessageDialog("Speichern erfolgreich").ShowAsync();
                    } else {
                        await new MessageDialog("Speichern fehlgeschlagen").ShowAsync();
                    }

                    Debug.WriteLine(status);
                }
            }
        }
예제 #27
0
        private async void Click_Me_Click(object sender, RoutedEventArgs e)
        {
            var szRequest = "Https://box.zjuqsc.com/item/get/";
            szRequest += Input.Text;
            Status.Text = "Sending request...\r\nPlease wait";
            HttpClient download = new HttpClient();
            HttpResponseMessage response;
            try
            {
                response = await download.GetAsync(new Uri(szRequest));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.GetType());
                Status.Text = "Connection Error\r\nPlease check your network";
                return;
            }
            var headers = response.Headers;
            var content = response.Content;
            Debug.WriteLine(response.StatusCode);
            var reg = new Regex("filename=\"(.+)\"");
            var mat = reg.Match(content.Headers.ToString());
            if ((HttpStatusCode)404 == response.StatusCode)
            {
                Status.Text = "Error occurred...\r\nCheck your Code\r\nor try again";
                return;
            }
            Status.Text = "Response Got,Saving File";
            var filename = mat.Groups[0].Value;
            Debug.WriteLine(filename);

            var picker = new FileSavePicker
            {
                SuggestedFileName = filename,
                SuggestedStartLocation = PickerLocationId.Downloads
            };
            //picker.FileTypeChoices.Add("Any File Type", new List<string>() { "." });
            picker.FileTypeChoices.Add(new KeyValuePair<string, IList<string>>("All File", new List<string> { "*" }));
            var file = await picker.PickSaveFileAsync();
            if (null != file)
            {
                Debug.WriteLine(file.ToString());
                var buffer = await content.ReadAsBufferAsync();
                var write = await file.OpenTransactedWriteAsync();
                await write.Stream.WriteAsync(buffer);
                await write.CommitAsync();
                Status.Text = filename + " has been saved.";
            }
            else
                Status.Text = "Error:\r\nCannot Open the file";


#if DEBUG
            Debug.WriteLine(content.Headers);
            Status.Text = content.Headers.ToString();
#endif
            download.Dispose();
        }
예제 #28
0
        private async void SaveVideo_Click(object sender, RoutedEventArgs e)
        {
            TokenSource.Dispose();
            TokenSource = new CancellationTokenSource();
            Token       = TokenSource.Token;

            var temp = saveResolutionSelector.SelectedItem as Resolutions;
            var enc  = _video.GetVideoEncodingProperties();

            MediaEncodingProfile mediaEncoding = GetMediaEncoding(temp, enc);

            Debug.WriteLine("Vid type: " + enc.Type);
            Debug.WriteLine("Vid sub: " + enc.Subtype);
            Debug.WriteLine("Vid id: " + enc.ProfileId);

            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 = "RenderedVideo.mp4";
            SaveProgressCallback saveProgress = ShowErrorMessage;

            Windows.Storage.StorageFile file = await picker.PickSaveFileAsync();

            if (file != null)
            {
                _mediaPlayer.Pause();

                ValuePairs.Remove("height");
                ValuePairs.Remove("width");

                ValuePairs.Add("height", temp.Resolution.Height);
                ValuePairs.Add("width", temp.Resolution.Width);

                if (_dotsFlag)
                {
                    ValuePairs.Remove("dotsRadius");
                    ValuePairs.Add("dotsRadius", (float)temp.Resolution.Width / 4096 * 20);
                }

                if (_horizonFlag)
                {
                    _composition.OverlayLayers[0] = await GenerateHorizonLayer((int)_video.TrimmedDuration.TotalSeconds, temp.Resolution.Height, temp.Resolution.Width);
                }

                //buttonLoadingStop.Visibility = Visibility.Visible;
                generateVideoButton.IsEnabled   = false;
                saveCompositionButton.IsEnabled = false;

                HeatmapGenerator generator = new HeatmapGenerator();

                generator.RenderCompositionToFile(file, _composition, saveProgress, Window.Current, mediaEncoding, Token, saveResolutionSelector.SelectedItem);
            }
        }
 public async Task GenerateDocx()
 {
     var fileSaver = new FileSavePicker();
     fileSaver.FileTypeChoices.Add("DocX file", new List<string> { ".docx" });
     fileSaver.DefaultFileExtension = ".docx";
     StorageFile file = await fileSaver.PickSaveFileAsync();
     if(file != null)
         await new BasicCvTemplate().GenerateCV(file, UserData, SelectedLanguage);
 }
예제 #30
0
파일: ChipIO.cs 프로젝트: patrickgh3/chip
        public static async void Save()
        {
            Color[][] toSave = PixDisplay.PreviousColors;
            var picker = new Windows.Storage.Pickers.FileSavePicker();
            picker.FileTypeChoices.Add("PNG image", new string[] { ".png" });
            picker.DefaultFileExtension = ".png";
            var file = await picker.PickSaveFileAsync();
            
            if (file != null)
            {
                System.Guid encoderId;
                switch (file.FileType) {
                    case ".png":
                    default:
                        encoderId = Windows.Graphics.Imaging.BitmapEncoder.PngEncoderId;
                        break;
                }
                var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
                stream.Size = 0;
                var encoder = await Windows.Graphics.Imaging.BitmapEncoder.CreateAsync(
                    encoderId,
                    stream
                    );


                uint width = (uint)toSave.Length;
                uint height = (uint)toSave[0].Length;
                byte[] pixels = new byte[width*height*4];
                int k = 0;
                for (int i=0; i<height; i++)
                {
                    for (int j=0; j<width; j++)
                    {
                        pixels[k++] = toSave[j][i].R;
                        pixels[k++] = toSave[j][i].G;
                        pixels[k++] = toSave[j][i].B;
                        pixels[k++] = toSave[j][i].A;

                    }
                }
                encoder.SetPixelData(
                    Windows.Graphics.Imaging.BitmapPixelFormat.Rgba8,
                    Windows.Graphics.Imaging.BitmapAlphaMode.Straight,
                    width,
                    height,
                    96,
                    96,
                    pixels
                    );
                try {
                    await encoder.FlushAsync();
                } catch (Exception err) {
                    Debug.WriteLine("Error encoding the file for save.");
                }
            }
        }
 private async void ExportDictionaryButtonClick(object sender, RoutedEventArgs e)
 {
     var fileSavePicker = new FileSavePicker();
     fileSavePicker.FileTypeChoices.Add(".txt", new List<string> { ".txt" });
     fileSavePicker.SettingsIdentifier = "picker1";
     
     var fileToSave = await fileSavePicker.PickSaveFileAsync();
     if (fileToSave == null) return;
     WritePadAPI.exportUserDictionary(fileToSave.Path);
 }
        private async void SaveImage(FileSavePicker savePicker)
        {
            var file = await savePicker.PickSaveFileAsync();
            if (file != null)
            {
                await SaveImageAsync(file);
            }

            SaveButton.IsEnabled = true;
        }
예제 #33
0
        private async void ExportDataButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            var fileSaver = new FileSavePicker();
            fileSaver.FileTypeChoices.Add("XML file", new List<string> { ".xml" });
            fileSaver.FileTypeChoices.Add("JSON file", new List<string> { ".json" });
            fileSaver.FileTypeChoices.Add("DocX file", new List<string> { ".docx" });
            fileSaver.DefaultFileExtension = ".xml";

            StorageFile file = await fileSaver.PickSaveFileAsync();
            ViewModel.ExportData(file);
        }
예제 #34
0
 /// <summary>
 /// Save a bitmap to a PNG file
 /// </summary>
 /// <param name="bitmap">bitmap</param>
 /// <param name="location">path</param>
 /// <param name="fileName">file name</param>
 /// <returns>FileUpdateStatus</returns>
 public static async Task<FileUpdateStatus> SaveToPngImage(this WriteableBitmap bitmap, PickerLocationId location, string fileName)
 {
     var savePicker = new FileSavePicker
     {
         SuggestedStartLocation = location
     };
     savePicker.FileTypeChoices.Add("Png Image", new[] { ".png" });
     savePicker.SuggestedFileName = fileName;
     StorageFile sFile = await savePicker.PickSaveFileAsync();
     return await WriteToStorageFile(bitmap, sFile);
 }
예제 #35
0
 private static async Task<IStorageFile> SaveFile(bool showPicker = true, string filenamePrefix="receipt")
 {
     if (!showPicker)
     {
         return await KnownFolders.PicturesLibrary.CreateFileAsync(filenamePrefix + DateTime.UtcNow.ToFileTimeUtc() + ".jpg",
             CreationCollisionOption.GenerateUniqueName); // this way it is not in app data
     }
     var savePicker = new FileSavePicker {SuggestedStartLocation = PickerLocationId.PicturesLibrary};
     savePicker.FileTypeChoices.Add("Images", new List<string> {".jpg", ".jpeg"});
     savePicker.SuggestedFileName = "receipt" + DateTime.UtcNow;
     return await savePicker.PickSaveFileAsync();
 }
예제 #36
0
        private async void OnSave(object sender, RoutedEventArgs e)
        {
            var fileSavePicker = new FileSavePicker();
            fileSavePicker.FileTypeChoices.Add("Ink", new [] { ".ink" });

            var outputFile = await fileSavePicker.PickSaveFileAsync();
            var outputStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite);

            await Canvas.InkPresenter.StrokeContainer.SaveAsync(outputStream);

            Canvas.InkPresenter.StrokeContainer.Clear();
        }
예제 #37
0
//        private async Task SaveAFile(string txt)
//        {
//            bool usedPicker = true;

//            FileSavePicker savePicker = null;
//            Windows.Storage.StorageFile file = null;

//#if IoTCore
//#else
//            savePicker = new Windows.Storage.Pickers.FileSavePicker();
//#endif

//            if (savePicker != null)
//            {
//                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";

//                file = await savePicker.PickSaveFileAsync();
//                if (file == null)
//                {
//                    PostMessage("SaveAFile", "Operation cancelled.");
//                    rcvr = null;
//                    return;
//                }
//            }

//            FileDetail rcvFile = await rcvr.ReadAsync();
//            if (rcvFile == null)
//            {
//                PostMessage("SaveAFile", "Operation failed.");
//                rcvr = null;
//                return;
//            }

//            if (savePicker != null)
//            {
//                 await file.RenameAsync(rcvFile.filename);
//            }
//            else
//            {
//                usedPicker = false;
//                Windows.Storage.StorageFolder storageFolder =
//                    Windows.Storage.ApplicationData.Current.LocalFolder;
//                file =
//                await storageFolder.CreateFileAsync(rcvFile.filename,
//                    Windows.Storage.CreationCollisionOption.ReplaceExisting);
//            }
//            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, rcvFile.txt);
//                // 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)
//                {
//                    PostMessage( "File " , file.Name + " was saved in \r\n" + file.Path);

//                }
//                else
//                {
//                    PostMessage( "File " , file.Name + " couldn't be saved.");
//                }

//            }

//            rcvr = null;
//        }

        private async Task SaveAFile2(FileDetail rcvFile)
        {
            FileSavePicker savePicker = null;

            Windows.Storage.StorageFile file = null;

            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 = rcvFile.filename;

            file = await savePicker.PickSaveFileAsync();

            if (file == null)
            {
                PostMessage("SaveAFile", "Operation cancelled.");
                return;
            }


            //await file.RenameAsync(rcvFile.filename);


            // 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, rcvFile.txt);

            // 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)
            {
                PostMessage("File ", file.Name + " was saved in \r\n" + file.Path);
            }
            else
            {
                PostMessage("File ", file.Name + " couldn't be saved.");
            }
        }
예제 #38
0
        private async void OnSaveAs(object sender, TappedRoutedEventArgs e)
        {
            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 = "RenderedComposition.mp4";

            Windows.Storage.StorageFile file = await picker.PickSaveFileAsync();

            if (file != null)
            {
                // Call RenderToFileAsync
                var saveOperation = mComposition.RenderToFileAsync(file, MediaTrimmingPreference.Precise);

                saveOperation.Progress = new AsyncOperationProgressHandler <TranscodeFailureReason, double>(async(info, progress) =>
                {
                    await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() =>
                    {
                        Debug.WriteLine(string.Format("Saving file... Progress: {0:F0}%", progress));
                    }));
                });
                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)
                            {
                                Debug.WriteLine("Saving was unsuccessful");
                            }
                            else
                            {
                                Debug.WriteLine("Trimmed clip saved to file");
                            }
                        }
                        finally
                        {
                            // Update UI whether the operation succeeded or not
                        }
                    }));
                });
            }
            else
            {
                Debug.WriteLine("User cancelled the file selection");
            }
        }
예제 #39
0
        async private void btnExportStatistics_Click(object sender, RoutedEventArgs e)
        {
            this.AppBars(false);

            try
            {
                var savePicker = new Windows.Storage.Pickers.FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                savePicker.FileTypeChoices.Add("Hyper Text Markup Language", new List <string>()
                {
                    ".html"
                });

                var file = await savePicker.PickSaveFileAsync();

                if (file != null)
                {
                    var thing = await file.OpenStreamForWriteAsync();

                    using (StreamWriter sw = new StreamWriter(thing.AsOutputStream().AsStreamForWrite()))
                    {
                        StringBuilder sb = new StringBuilder(
                            @"<table>
<tbody>
<tr><th><span><span><b>Regular Season Individual Stats</b></span></span></th></tr><tr style=""background-color:#D49E09""><th style=""width: 200px"">Name</th><th style=""width: 80px"">Team</th><th style=""text-align: right; width: 40px"">G</th><th style=""text-align: right; width: 40px"">A</th><th style=""text-align: right; width: 40px"">Pts</th><th style=""text-align: right; width: 40px"">PM</th></tr>
");
                        int i = 0;
                        foreach (var p in pnlStats.Players)
                        {
                            if (i % 2 == 1)
                            {
                                sb.AppendLine(p.ToHtmlRow("#F4BE29"));
                            }
                            else
                            {
                                sb.AppendLine(p.ToHtmlRow(null));
                            }
                            i++;
                        }
                        sb.AppendLine("</tbody>");
                        sb.AppendLine("</table>");

                        sw.Write(sb.ToString());
                    }
                }
            }
            catch
            {
                var dialog = new MessageDialog("Error occured exporting standins.");
                dialog.ShowAsync();
            }
        }
예제 #40
0
        private async void Save(object sender, RoutedEventArgs e)
        {
            User user = new User();

            user.name  = this.name.Text;
            user.email = this.email.Text;
            user.sdt   = this.sdt.Text;
            user.dc    = this.dc.Text;
            string Jsonmember = JsonConvert.SerializeObject(user);

            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";

            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, Jsonmember);

                // 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)
                {
                    this.mess.Text = "File " + file.Name + " was saved.";
                }
                else
                {
                    this.mess.Text = "File " + file.Name + " couldn't be saved.";
                }
            }
            else
            {
                this.mess.Text = "Operation cancelled.";
            }
        }
예제 #41
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="defaultExt">limiteExt must not include it</param>
 /// <param name="limitExt"> e.g: ".txt" -> "Plain text"</param>
 /// <returns></returns>
 public async Task<StorageFile> PickFileToSave(string defaultFilename, string defaultExt, params KeyValuePair<string, string>[] limitExt)
 {
     var picker = new FileSavePicker();
     picker.DefaultFileExtension = defaultExt;
     picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
     picker.SuggestedFileName = defaultFilename;
     foreach (var ext in limitExt)
     {
         picker.FileTypeChoices.Add(ext.Value, new List<string>() { ext.Key });
     }
     StorageFile file = await picker.PickSaveFileAsync();
     return file;
 }
        private async void save_btn_Click(object sender, RoutedEventArgs e)
        {
            string document;

            //Get the text and put it in the "document" var, can then use it as a string of text!
            editBox.Document.GetText(Windows.UI.Text.TextGetOptions.AdjustCrlf, out document);
            if (!string.IsNullOrEmpty(document))
            {
                Windows.Storage.Pickers.FileSavePicker 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("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);

                    editBox.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();
                    }
                }
            }
            else
            {
                Windows.UI.Popups.MessageDialog error = new Windows.UI.Popups.MessageDialog("There is nothing to save!!!");
                await error.ShowAsync();
            }
        }
예제 #43
0
        private async void OnExportSelectedToExcel(object sender, RoutedEventArgs e) {
            ExcelEngine excelEngine = new ExcelEngine();
            var workBook = excelEngine.Excel.Workbooks.Create();
            workBook.Version = ExcelVersion.Excel2010;
            workBook.Worksheets.Create();

            if ((bool)this.customizeSelectedRow.IsChecked) {
                this.sfDataGrid.ExportToExcel(this.sfDataGrid.SelectedItems, new ExcelExportingOptions() {
                    CellsExportingEventHandler = CellExportingHandler,
                    ExportingEventHandler = CustomizedexportingHandler
                }, workBook.Worksheets[0]);
            }
            else {
                this.sfDataGrid.ExportToExcel(this.sfDataGrid.SelectedItems, new ExcelExportingOptions() {
                    CellsExportingEventHandler = CellExportingHandler,
                    ExportingEventHandler = exportingHandler
                }, workBook.Worksheets[0]);
            }

            workBook = excelEngine.Excel.Workbooks[0];
            var savePicker = new FileSavePicker {
                SuggestedStartLocation = PickerLocationId.Desktop,
                SuggestedFileName = "Sample"
            };

            if (workBook.Version == ExcelVersion.Excel97to2003) {
                savePicker.FileTypeChoices.Add("Excel File (.xls)", new List<string>() { ".xls" });
            }
            else {
                savePicker.FileTypeChoices.Add("Excel File (.xlsx)", new List<string>() { ".xlsx" });
            }

            var storageFile = await savePicker.PickSaveFileAsync();

            if (storageFile != null) {
                await workBook.SaveAsAsync(storageFile);

                var msgDialog = new MessageDialog("Do you want to view the Document?", "File has been created successfully.");

                var yesCmd = new UICommand("Yes");
                var noCmd = new UICommand("No");
                msgDialog.Commands.Add(yesCmd);
                msgDialog.Commands.Add(noCmd);
                var cmd = await msgDialog.ShowAsync();
                if (cmd == yesCmd) {
                    // Launch the saved file
                    bool success = await Windows.System.Launcher.LaunchFileAsync(storageFile);
                }
            }
            excelEngine.Dispose();
        }
예제 #44
0
 private async void Button_Click_1(object sender, RoutedEventArgs e)
 {
     var picker = new FileSavePicker();
     picker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
     picker.FileTypeChoices.Add("WMVファイル", new List<string>(new string[1] { ".wmv" }));
     picker.SuggestedFileName = "output.wmv";
     var file = await picker.PickSaveFileAsync();
     if (file != null)
     {
         await Write(file);
         MessageDialog dialog = new MessageDialog("書き出しが終了しました");
         await dialog.ShowAsync();
     }
 }
예제 #45
0
 private async void SaveButton_Click(object sender, RoutedEventArgs e)
 {
     FileSavePicker savePicker = new FileSavePicker();
     savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
     savePicker.FileTypeChoices.Add("Bitmap", new List<string>() { ".bmp" });
     savePicker.FileTypeChoices.Add("Graphical Interchange Format", new List<string>() { ".gif" });
     savePicker.FileTypeChoices.Add("Joint Photographic Experts Group", new List<string>() { ".jpg" });
     savePicker.FileTypeChoices.Add("Portable Network Graphics", new List<string>() { ".png" });
     var file = await savePicker.PickSaveFileAsync();
     if (file != null)
     {
         await (this.CroppedImage.Source as WriteableBitmap).SaveAsync(file);
     }
 }
예제 #46
0
        private async void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            var fileSave = new FileSavePicker();
            fileSave.FileTypeChoices.Add("Gif with embedded ISF", new List<string> { ".gif" });

            var storageFile = await fileSave.PickSaveFileAsync();

            if (storageFile != null)
            {
                using (var stream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await this.InkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream);
                }
            }
        }
        async void OnSaveAsAppBarButtonClick(object sender, RoutedEventArgs args)
        {
            FileSavePicker picker = new FileSavePicker();
            picker.DefaultFileExtension = ".txt";
            picker.FileTypeChoices.Add("Text", new List<string> { ".txt" });

            // Asynchronous call!
            StorageFile storageFile = await picker.PickSaveFileAsync();

            if (storageFile == null)
                return;

            // Asynchronous call!
            await FileIO.WriteTextAsync(storageFile, txtbox.Text);
        }
        private async Task PerformSave(PDFDoc doc)
        {
            // Start File Picker so we can SaveAs/Export document
            var savePicker = new Windows.Storage.Pickers.FileSavePicker();

            savePicker.FileTypeChoices.Add("PDF", new List <string> {
                ".pdf"
            });

            var storageFile = await savePicker.PickSaveFileAsync();

            if (storageFile != null)
            {
                await doc.SaveToNewLocationAsync(storageFile, pdftron.SDF.SDFDocSaveOptions.e_incremental);
            }
        }
예제 #49
0
        private async void SaveButton_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";
            Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                Windows.Storage.CachedFileManager.DeferUpdates(file);
                await Windows.Storage.FileIO.WriteTextAsync(file, file.Name);

                if (complock == Complexity.Simple && pagePerson != null)
                {
                    await Windows.Storage.FileIO.WriteTextAsync(file, pagePerson.ToString());
                }
                else if (complock == Complexity.ModeratlyComplex && pagePerson != null)
                {
                    await Windows.Storage.FileIO.WriteTextAsync(file, pagePerson.ToString());
                }
                else if (complock == Complexity.ModeratlyComplexTableTop && pagePerson != null)
                {
                    await Windows.Storage.FileIO.WriteTextAsync(file, pagePerson.ToString());
                }
                else if (complock == Complexity.Complex && pagePerson != null)
                {
                    await Windows.Storage.FileIO.WriteTextAsync(file, pagePerson.ToString());
                }
                else if (complock == Complexity.ComplexTableTop && pagePerson != null)
                {
                    await Windows.Storage.FileIO.WriteTextAsync(file, pagePerson.ToString());
                }

                Windows.Storage.Provider.FileUpdateStatus status =
                    await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);
            }
        }
예제 #50
0
        private async void savebtn_Click(object sender, RoutedEventArgs e)
        {
            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 = "RenderedComposition.mp4";

            Windows.Storage.StorageFile pickedFile = await picker.PickSaveFileAsync();

            if (pickedFile != null)
            {
                // Call RenderToFileAsync
                var saveOperation = composition.RenderToFileAsync(pickedFile, MediaTrimmingPreference.Precise);


                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)
                            {
                                //ShowErrorMessage("Saving was unsuccessful");
                            }
                            else
                            {
                                // ShowErrorMessage("Trimmed clip saved to file");

                                mediaElement.Source = null;
                                savebtn.IsEnabled   = false;
                            }
                        }
                        finally
                        {
                        }
                    }));
                });
            }
        }
예제 #51
0
        private async Task <IStorageFile> PromptSaveDialoge(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return(null);
            }

            // Start File Picker so we can SaveAs/Export document
            var savePicker = new Windows.Storage.Pickers.FileSavePicker();

            savePicker.FileTypeChoices.Add(name, new List <string> {
                ".docx"
            });

            var storageFile = await savePicker.PickSaveFileAsync();

            return(storageFile);
        }
예제 #52
0
        internal static async Task SaveAppStateToUserDefinedLocation(AppState appState)
        {
            var savePicker = new Windows.Storage.Pickers.FileSavePicker();

            savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            savePicker.FileTypeChoices.Add("Plain Text", new List <string>()
            {
                ".xml"
            });
            savePicker.SuggestedFileName = "HomeAutomationSettings";

            Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                var token = StorageApplicationPermissions.FutureAccessList.Add(file, _userDefinedSettingsToken);
                LocalSettings.Values[_userDefinedSettingsToken] = token;

                // Prevent updates to the remote version of the file until
                // we finish making changes and call CompleteUpdatesAsync.
                //Windows.Storage.CachedFileManager.DeferUpdates(file);  crashes when used with dropbox
                // write to file
                await XMLStorage.SaveObjectToXmlByFile(appState, 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.
                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 + " couldn't be saved.");
                }
            }
            else
            {
                Debug.WriteLine("Saving file was cancelled.");
            }
        }
예제 #53
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");
                }
                //}
            }
        }
예제 #54
0
        private async Task SaveInkAsync()
        {
            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 List <string> {
                    ".gif"
                });

                var file = await savePicker.PickSaveFileAsync();

                if (null != file)
                {
                    using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        // This single method will get all the strokes and save them to the file
                        await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream);
                    }
                }
            }
        }
예제 #55
0
        private async void btn_write_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)
            {
                filename = txt_filename.Text;
                String content = txt_content.Text;
                FilehanderService.WriteFile(filename + ".txt", content);
            }
        }
예제 #56
0
        private async ValueTask SaveAsFileAsync()
        {
            var savePicker = new Windows.Storage.Pickers.FileSavePicker
            {
                SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary,
                SuggestedFileName      = "Новый текстовый документ"
            };

            // 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

            _editedFile = await savePicker.PickSaveFileAsync();

            if (_editedFile != null)
            {
                await SaveFileAsync();
            }
        }
예제 #57
0
        async private void btnExportStandings_Click(object sender, RoutedEventArgs e)
        {
            this.AppBars(false);

            try
            {
                var savePicker = new Windows.Storage.Pickers.FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                savePicker.FileTypeChoices.Add("Hyper Text Markup Language", new List <string>()
                {
                    ".html"
                });

                var file = await savePicker.PickSaveFileAsync();

                if (file != null)
                {
                    var thing = await file.OpenStreamForWriteAsync();

                    using (StreamWriter sw = new StreamWriter(thing.AsOutputStream().AsStreamForWrite()))
                    {
                        StringBuilder sb = new StringBuilder(
                            @"<table>
    <tbody>
        <tr>
            <th>
                <span>
                    <span>
                        <b>Regular Season Standings</b>
                    </span>
                </span>
            </th>
        </tr>
        <tr style=""background-color: #D49E09"">
            <th style=""width: 200px"">Team</th>
            <th style=""text-align: right; width: 30px"">G</th>
            <th style=""text-align: right; width: 30px"">W</th>
            <th style=""text-align: right; width: 30px"">L</th>
            <th style=""text-align: right; width: 30px"">T</th>
            <th style=""text-align: right; width: 30px"">PT</th>
            <th style=""text-align: right; width: 30px"">GF</th>
            <th style=""text-align: right; width: 30px"">GA</th>
            <th style=""text-align: right; width: 50px"">GAS</th>
        </tr>");
                        int i = 0;



                        foreach (var p in pnlStandings.Teams.OrderByDescending(t => t.AverageGoalsScoredPerGame).OrderByDescending(t => t.Points))
                        {
                            if (i % 2 == 1)
                            {
                                sb.AppendLine(p.ToHtmlRow("#F4BE29"));
                            }
                            else
                            {
                                sb.AppendLine(p.ToHtmlRow(null));
                            }
                            i++;
                        }
                        sb.AppendLine("</tbody>");
                        sb.AppendLine("</table>");
                        sb.AppendLine("<p></p>");
                        sb.Append(
                            @"<table>
    <tbody>
        <tr>
            <th>
                <span>
                    <span>
                        <b>Latest Game Results</b>
                    </span>
                </span>
            </th>
        </tr>
        <tr style=""background-color:#D49E09"">
            <th style=""width: 180px"">Home</th>
            <th style=""text-align: right; width: 30px""/>
            <th style=""width: 30px""/>
            <th style=""width: 180px"">Visitor</th>
            <th style=""text-align: right; width: 30px""/>
        </tr>");
                        i = 0;
                        foreach (var p in pnlStandings.Games.OrderByDescending(t => t.Date).Take((pnlStandings.Teams.Count + 1) / 2))
                        {
                            if (i % 2 == 1)
                            {
                                sb.AppendLine(p.ToHtmlRow("#F4BE29", pnlStandings.Teams));
                            }
                            else
                            {
                                sb.AppendLine(p.ToHtmlRow(null, pnlStandings.Teams));
                            }
                            i++;
                        }
                        sb.AppendLine("</tbody>");
                        sb.AppendLine("</table>");

                        sw.Write(sb.ToString());
                    }
                }
            }
            catch
            {
                var dialog = new MessageDialog("Error occured exporting statistics.");
                dialog.ShowAsync();
            }
        }
        private async Task savesubreddits_clickasync()
        {
            Regex url_rx = new Regex(@"(?:^(?:https?:\/\/)?(?:www.)?(?:(?:np|np-dk).)?(?:reddit\.com)\/r\/([a-zA-Z0-9_]+)\/?|^(?:\/?r\/)?([a-zA-Z0-9_]+))", RegexOptions.Compiled);

            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 = "AutoSlide Subreddit List " + new DateTime();

            StorageFile file = await savePicker.PickSaveFileAsync();

            Stream       x;
            StreamWriter writer;

            if (file != null)
            {
                try
                {
                    x = await file.OpenStreamForWriteAsync();

                    writer = new StreamWriter(x, Encoding.UTF8);
                    try
                    {
                        foreach (String s in LinkList.Where((Link link) => { return(url_rx.IsMatch(link.Url)); }).Select((Link a) => { return(a.Url); }))
                        {
                            await writer.WriteLineAsync(s);
                        }
                        await writer.FlushAsync();
                    }
                    finally
                    {
                        writer.Dispose();
                        x.Dispose();
                    }
                }
                catch (PathTooLongException)
                {
                    ShowMessageDialog("File Saving Error", "Unfortunately we couldn't save the file as the path was too long. Please try using a shorter path.");
                    return;
                }
                catch (NotSupportedException)
                {
                    ShowMessageDialog("File Saving Error", "Unfortunately we couldn't save the file as file saving is not supported on this platform. Apologies for the inconvenience.");
                    return;
                }
                catch (DirectoryNotFoundException)
                {
                    ShowMessageDialog("File Saving Error", "Unfortunately we couldn't save the file as we couldn't find the directory. Please try using a different directory.");
                    return;
                }
                catch (SecurityException)
                {
                    ShowMessageDialog("File Saving Error", "Unfortunately we couldn't save the file due to security issues. Please send the error code SEC1 to the developer for support.");
                    return;
                }
                catch (UnauthorizedAccessException)
                {
                    ShowMessageDialog("File Saving Error", "Unfortunately we couldn't save the file as access to that file is not authorized on this account. Please try again with higher priveleges or save to a different directory.");
                    return;
                }
                catch (IOException)
                {
                    ShowMessageDialog("File Saving Error", "Unfortunately we couldn't save the file. Please send the error code IOE1 to the developer for support.");
                    return;
                }
                ShowMessageDialog("Subreddit list Saved!", "We have saved your subreddit list to " + file.Path + ".");
            }
        }
예제 #59
0
        private async void ButtonGo_Click(object sender, RoutedEventArgs e)
        {
            if (imageDescript.file != null && !string.IsNullOrWhiteSpace(ParameterMessageToFindLenght.Text) && !string.IsNullOrWhiteSpace(ParameterMessageToFindStart.Text) && !string.IsNullOrWhiteSpace(ParameterMessageSkippingBytes.Text))
            {
                LoadingIndicator.IsActive = true;
                imageDescript.ClearMessage();
                imageDescript.NBytesOffset = Convert.ToInt32(ParameterMessageSkippingBytes.Text);
                if (ParameterMessageToFindLenght.Text.Length == 0)//verify if there is an input
                {
                    imageDescript.deb("You should enter a size");
                    imageDescript.LenghtMessageToShow = 500;//placeholder input
                }
                else
                {
                    imageDescript.LenghtMessageToShow = Convert.ToInt32(ParameterMessageToFindLenght.Text);
                }
                if (ParameterMessageToFindStart.Text.Length != 0)
                {
                    imageDescript.StartAtPosition = Int32.Parse(ParameterMessageToFindStart.Text);
                }
                else
                {
                    imageDescript.StartAtPosition = 0;
                }
                if (GetFileBool == true)
                {
                    imageDescript.LenghtFile = Int32.Parse(ParameterMessageToFindLenght.Text);
                    byte[] newFile = await imageDescript.OperationGetHiddenFile();

                    //Sytem de Sauvegarde
                    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("bitmap", new List <string>()
                    {
                        ".bmp"
                    });
                    // Default file name if the user does not type one in or select a file to replace
                    savePicker.SuggestedFileName = "Newpicturefromanother";


                    Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();

                    if (file != null)
                    {
                        await FileIO.WriteBytesAsync(file, newFile);

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

                        if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
                        {
                            this.ReponseForSaveFile.Text = "File " + file.Name + " was saved.";
                        }
                        else
                        {
                            this.ReponseForSaveFile.Text = "File " + file.Name + " couldn't be saved.";
                        }
                    }
                    else
                    {
                        this.ReponseForSaveFile.Text = "Operation cancelled.";
                    }
                }
                else
                {
                    MessageDecoder = await imageDescript.OperationRead();

                    Result.Text = MessageDecoder;
                }
            }
            LoadingIndicator.IsActive = false;
        }
예제 #60
0
        private async void ButtonGo_Click(object sender, RoutedEventArgs e)
        {
            //Sytem de Sauvegarde
            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("Bitmap", new List <string>()
            {
                ".bmp"
            });
            // Default file name if the user does not type one in or select a file to replace
            savePicker.SuggestedFileName = "VacationPictures";


            if (fileEncrypted.file != null && !string.IsNullOrWhiteSpace(messageToHide.Text) && !string.IsNullOrWhiteSpace(ParameterMessageToFindStart.Text) && !string.IsNullOrWhiteSpace(ParameterMessageSkippingBytes.Text))
            {
                LoadingIndicator.IsActive  = true;
                fileEncrypted.NBytesOffset = Int32.Parse(ParameterMessageSkippingBytes.Text);
                if (ParameterMessageToFindStart.Text.Length != 0)
                {
                    fileEncrypted.StartAtPosition = Int32.Parse(ParameterMessageToFindStart.Text);
                }
                else
                {
                    fileEncrypted.StartAtPosition = 0;
                }

                if (MessageToHideBool)
                {
                    fileEncrypted.MessageToHide = messageToHide.Text;
                }
                else
                {
                    IBuffer bufferToHide = await FileIO.ReadBufferAsync(fileToHide);

                    byte[] fileToHideBytes = bufferToHide.ToArray();
                    fileEncrypted.MessageByte = fileToHideBytes;
                }

                fileEncrypted.MessageToAscii(MessageToHideBool);
                Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();



                if (file != null)
                {
                    await FileIO.WriteBytesAsync(file, fileEncrypted.FinalsFiles);

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

                    if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
                    {
                        this.test.Text = "File " + file.Name + " was saved.";
                    }
                    else
                    {
                        this.test.Text = "File " + file.Name + " couldn't be saved.";
                    }
                }
                else
                {
                    this.test.Text = "Operation cancelled.";
                }
            }
            LoadingIndicator.IsActive = false;
        }