CopyAndReplaceAsync() public method

public CopyAndReplaceAsync ( [ fileToReplace ) : IAsyncAction
fileToReplace [
return IAsyncAction
示例#1
0
        public static async Task ResizeImageUniformAsync(StorageFile sourceFile, StorageFile targetFile, int maxWidth = Int32.MaxValue, int maxHeight = Int32.MaxValue)
        {
            using (var stream = await sourceFile.OpenReadAsync())
            {
                var decoder = await BitmapDecoder.CreateAsync(stream);

                if (IsGifImage(decoder))
                {
                    await sourceFile.CopyAndReplaceAsync(targetFile);
                    return;
                }

                maxWidth = Math.Min(maxWidth, (int)decoder.OrientedPixelWidth);
                maxHeight = Math.Min(maxHeight, (int)decoder.OrientedPixelHeight);
                var imageSize = new Size(decoder.OrientedPixelWidth, decoder.OrientedPixelHeight);
                var finalSize = imageSize.ToUniform(new Size(maxWidth, maxHeight));

                if (finalSize.Width == decoder.OrientedPixelWidth && finalSize.Height == decoder.OrientedPixelHeight)
                {
                    await sourceFile.CopyAndReplaceAsync(targetFile);
                    return;
                }

                await ResizeImageAsync(decoder, targetFile, finalSize);
            }
        }
        private async void CoverPlaylist_Click(object sender, RoutedEventArgs e)
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker();

            picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
            picker.FileTypeFilter.Add(".jpg");
            picker.FileTypeFilter.Add(".png");

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

            if (file != null)
            {
                StorageFile cover;
                try
                {
                    cover = await file.CopyAsync(StaticContent.CoversFolder);
                }
                catch
                {
                    cover = await StaticContent.CoversFolder.GetFileAsync(file.Name);

                    await file.CopyAndReplaceAsync(cover);
                }

                Playlist.Cover       = cover.Path;
                CoverImage.UriSource = new Uri(Playlist.Cover);
            }
            else
            {
            }
        }
示例#3
0
        private async void Button_Click_3(object sender, RoutedEventArgs e)
        {
            Windows.Storage.Pickers.FileOpenPicker openPicker = new Windows.Storage.Pickers.FileOpenPicker();
            openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
            openPicker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;

            // Filter to include a sample subset of file types.
            openPicker.FileTypeFilter.Clear();
            openPicker.FileTypeFilter.Add(".bmp");
            openPicker.FileTypeFilter.Add(".png");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".jpg");

            // Open the file picker.
            Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync();

            // file is null if user cancels the file picker.
            if (file != null)
            {
                // Open a stream for the selected file.
                Windows.Storage.Streams.IRandomAccessStream fileStream =
                    await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

                // Set the image source to the selected bitmap.
                Windows.UI.Xaml.Media.Imaging.BitmapImage bitmapImage =
                    new Windows.UI.Xaml.Media.Imaging.BitmapImage();

                bitmapImage.SetSource(fileStream);
                displayImage.Source = bitmapImage;

                this.DataContext = file;
            }

            try
            {
                var db     = new SQLite.SQLiteConnection(App.DBPath);
                var emptab = (db.Table <lawyer>().Where(em => em.username == txt1.Text)).Single();

                var targetFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(emptab.username + ".jpg");

                if (targetFile != null)
                {
                    //await file.MoveAndReplaceAsync(targetFile);
                    await file.CopyAndReplaceAsync(targetFile);
                }
            }
            catch (Exception ex)
            {
                var var_name = new MessageDialog("Unable to update profile picture\nPlease try after sometime.");
                var_name.Commands.Add(new UICommand("OK"));
                var_name.ShowAsync();
            }

            // await file.CopyAsync(ApplicationData.Current.LocalFolder);
        }
示例#4
0
        public static async Task<StorageFile> CreateCopyOfSelectedImage(StorageFile file)
        {
            var newSourceFileName = string.Format(@"{0}.jpg", Guid.NewGuid());
            var newSourceFile =
                await
                    ApplicationData.Current.TemporaryFolder.CreateFileAsync(newSourceFileName,
                        CreationCollisionOption.ReplaceExisting);
            await file.CopyAndReplaceAsync(newSourceFile);

            return newSourceFile;
        }
 private async Task CopyImageToLocalFolderAsync(StorageFile file)
 {
     OutputTextBlock.Text = string.Empty;
     if (file != null)
     {
         StorageFile newFile = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(file.Name, Windows.Storage.CreationCollisionOption.GenerateUniqueName);
         await file.CopyAndReplaceAsync(newFile);
         this.imageRelativePath = newFile.Path.Substring(newFile.Path.LastIndexOf("\\") + 1);
         rootPage.NotifyUser("Image copied to application data local storage: " + newFile.Path, NotifyType.StatusMessage);
     }
     else
     {
         rootPage.NotifyUser("File was not copied due to error or cancelled by user.", NotifyType.ErrorMessage);
     }
 }
        private async void ValidateXMLButton_Click(object sender, RoutedEventArgs e)
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker
            {
                ViewMode = Windows.Storage.Pickers.PickerViewMode.List,
                SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.ComputerFolder
            };

            picker.FileTypeFilter.Add(".xml");
            Windows.Storage.StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            StorageFile tempXml = await localFolder.CreateFileAsync("temp.xml", CreationCollisionOption.ReplaceExisting);

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

            if (file != null)
            {
                var path = file.Path;
                await file.CopyAndReplaceAsync(tempXml);

                try
                {
                    FactoryOrchestratorXML.Load(tempXml.Path);

                    ContentDialog successLoadDialog = new ContentDialog
                    {
                        Title           = resourceLoader.GetString("XmlValidatedTitle"),
                        Content         = string.Format(CultureInfo.CurrentCulture, resourceLoader.GetString("XmlValidatedContent"), path),
                        CloseButtonText = resourceLoader.GetString("Ok")
                    };

                    _ = await successLoadDialog.ShowAsync();
                }
                catch (Exception ex)
                {
                    var           msg = ex.AllExceptionsToString().Replace(tempXml.Path, path, StringComparison.OrdinalIgnoreCase);
                    ContentDialog failedLoadDialog = new ContentDialog
                    {
                        Title           = resourceLoader.GetString("XmlFailedTitle"),
                        Content         = msg,
                        CloseButtonText = resourceLoader.GetString("Ok")
                    };

                    _ = await failedLoadDialog.ShowAsync();
                }
            }
        }
示例#7
0
        private CreatePlaylistViewModel()
        {
            CreatePlaylist = new RelayCommand(async() =>
            {
                if (StaticContent.Playlists.Count >= 15 && StaticContent.IsPro == false)
                {
                    await new MessageDialog("У Вас уже есть 15 плейлистов. Для того, чтобы создать больше 15 плейлистов, необходимо купить MusicX Pro", "Купите MusicX Pro").ShowAsync();
                }
                else
                {
                    try
                    {
                        var playlist = new PlaylistFile()
                        {
                            Artist      = "Music X",
                            Cover       = ImagePlaylist,
                            Id          = new Random().Next(10, 1234),
                            Name        = NamePlaylist,
                            TracksFiles = new List <AudioFile>(),
                            IsLocal     = true
                        };

                        await PlaylistsService.SavePlaylist(playlist);
                        StaticContent.Playlists.Add(playlist);
                        VisibilityGridCreate = Visibility.Collapsed;
                        VisibilityGridDone   = Visibility.Visible;
                        NamePlaylist         = "";
                        Changed("NamePlaylist");
                    }
                    catch (Exception e)
                    {
                        await ContentDialogService.Show(new ExceptionDialog("Невозможно создать плейлист", "Возможно, такой плейлист уже существует. Попробуйте ещё раз.", e));
                    }
                }
            });

            SelectCover = new RelayCommand(async() =>
            {
                try
                {
                    var picker      = new Windows.Storage.Pickers.FileOpenPicker();
                    picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
                    picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
                    picker.FileTypeFilter.Add(".jpg");
                    picker.FileTypeFilter.Add(".png");

                    Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
                    if (file != null)
                    {
                        StorageFile cover;
                        try
                        {
                            cover = await file.CopyAsync(StaticContent.CoversFolder);
                        }
                        catch
                        {
                            cover = await StaticContent.CoversFolder.GetFileAsync(file.Name);
                            await file.CopyAndReplaceAsync(cover);
                        }

                        ImagePlaylist = cover.Path;
                    }
                    else
                    {
                    }
                }catch (Exception e)
                {
                    await ContentDialogService.Show(new ExceptionDialog("Ошибка при выборе файла", "Неизвестная ошибка", e));
                }
            });

            visibilityGridCreate = Visibility.Visible;
            visibilityGridDone   = Visibility.Collapsed;
        }
示例#8
0
        /// <summary>
        /// Permissions needed: Webcam, Microphone, PicturesLibrary, VideosLibrary
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            // Capture photo
            var camera = new CameraCaptureUI();
            image = await camera.CaptureFileAsync(CameraCaptureUIMode.Photo);

            DisplayNotification("Photo captured", "Hey good lookin'");

            // Save image to Pictures Library
            var saveImageFile = await KnownFolders.PicturesLibrary.CreateFileAsync("test.jpg", CreationCollisionOption.ReplaceExisting);
            await image.CopyAndReplaceAsync(saveImageFile);

            DisplayNotification("Photo saved", "test.jpg");
        }
 public async void SetNewImage(StorageFile originalFile)
 {
     if (originalFile != null)
     {
         var newFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(originalFile.Name, CreationCollisionOption.GenerateUniqueName);
         await originalFile.CopyAndReplaceAsync(newFile);
         Image = newFile.Path;
     }
 }
        private async void file2SoftwareBitmapSource(StorageFile file, int index = 0, bool isAddImage = false)
        {
            if (!isAddImage)
            {
                IStorageFolder applicationFolder = ApplicationData.Current.TemporaryFolder;
                await file.CopyAndReplaceAsync(await applicationFolder.CreateFileAsync(file.Name, CreationCollisionOption.ReplaceExisting));
            }

            SoftwareBitmapSource source = new SoftwareBitmapSource();
            SoftwareBitmap sb = null;
            using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
                SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
                sb = softwareBitmap;
            }
            await source.SetBitmapAsync(sb);
            imageList.Insert(index, new CommunityImageList { imgUri = source, imgName = file.Name, imgPath = file.Path, imgAppPath = "ms-appdata:///Temp/" + file.Name });
        }
示例#11
0
 public static async Task ImportTimetable(StorageFile file)
 {
     var fileName = await ReserveNewTimetableFilename();
     var destinationFile = await (await GetTimetableDirectory()).GetFileAsync(fileName);
     try
     {
         await file.CopyAndReplaceAsync(destinationFile);
         Timetable.ParseXml(await FileIO.ReadTextAsync(destinationFile), fileName, Strings.TimetableNewName);
         return;
     }
     catch  { }
     await destinationFile.DeleteAsync();
     await new MessageDialog(Strings.TimetableIOImportError, Strings.MessageBoxWarningCaption).ShowAsync();
 }
示例#12
0
        private async void SaveFileOnPc_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("ehw file", new List <string>()
            {
                ".ehw"
            });
            // Default file name if the user does not type one in or select a file to replace
            savePicker.SuggestedFileName = "New Document";


            // read my file which I want to save

            string fileName = SelectedFile.Text;

            if (fileName.Length < 1)
            {
                ("Error: You have not selected a file.").Show();
                return;
            }


            Windows.Storage.StorageFolder storageFolder =
                Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile sampleFile =
                await storageFolder.GetFileAsync(fileName);


            string text = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);

            string textToSave = text.EncryptStr();

            // var buffer = await Windows.Storage.FileIO.ReadBufferAsync(sampleFile);


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

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


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

                //  await Windows.Storage.FileIO.WriteBufferAsync(file, buffer);


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

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