private CopyAsync ( [ destinationFolder ) : IAsyncOperation |
||
destinationFolder | [ | |
Résultat | IAsyncOperation |
public async void ParseData(StorageFile file) { try { if (!await FileUtil.DirExistsAsync(ConstantsAPI.SDK_TEMP_DIR_PATH)) { await FileUtil.CreateDirAsync(ConstantsAPI.SDK_TEMP_DIR_PATH); } var folder = await ApplicationData.Current.LocalFolder.GetFolderAsync(ConstantsAPI.SDK_TEMP_DIR_PATH); var copyFile = await file.CopyAsync(folder, "wp.wechat", NameCollisionOption.ReplaceExisting); if (await FileUtil.FileExistsAsync(ConstantsAPI.SDK_TEMP_FILE_PATH)) { TransactData data = await TransactData.ReadFromFileAsync(ConstantsAPI.SDK_TEMP_FILE_PATH); if (!data.ValidateData()) { //MessageBox.Show("数据验证失败"); } else if (!data.CheckSupported()) { //MessageBox.Show("当前版本不支持该请求"); } else if (data.Req != null) { if (data.Req.Type() == ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX) { OnGetMessageFromWXRequest(data.Req as GetMessageFromWX.Req); } else if (data.Req.Type() == 4) { OnShowMessageFromWXRequest(data.Req as ShowMessageFromWX.Req); } } else if (data.Resp != null) { if (data.Resp.Type() == 1) { OnSendAuthResponse(data.Resp as SendAuth.Resp); } else if (data.Resp.Type() == 2) { OnSendMessageToWXResponse(data.Resp as SendMessageToWX.Resp); } else if (data.Resp.Type() == 5) { OnSendPayResponse(data.Resp as SendPay.Resp); } } } } catch (Exception ex) { Debug.WriteLine(ex.Message); //MessageBox.Show(exception.Message); } }
public static async Task copysample() { Uri uri = new Uri("ms-appx:///Assets/ab.png"); Windows.Storage.StorageFile file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri); Windows.Storage.StorageFile copiedfile = await file.CopyAsync(Windows.Storage.ApplicationData.Current.LocalFolder, "ab.png"); await Routines.extractFiles(copiedfile); uri = new Uri("ms-appdata:///local/ab/OPS/images/cover.png"); file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri); Windows.Storage.StorageFolder imageFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFolderAsync("thumbs"); await file.CopyAsync(imageFolder, "book0.jpg"); var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; Windows.Storage.ApplicationDataCompositeValue composite = new Windows.Storage.ApplicationDataCompositeValue(); composite["uniqueid"] = "book0"; composite["title"] = "The Arabian Nights"; composite["author"] = "Andrew Lang"; composite["image"] = "thumbs\\book0.jpg";; composite["location"] = "ab"; var samplebook = new Book(composite["uniqueid"].ToString(), composite["title"].ToString(), composite["author"].ToString(), composite["image"].ToString(), composite["location"].ToString()); BookSource.AddBookAsync(samplebook); int count = (int)localSettings.Values["bookCount"]; localSettings.Values["bookCount"] = ++count; localSettings.Containers["booksContainer"].Values["book0"] = composite; }
public async static Task CreatePageFiles(StorageFile fileToCopy, Guid pageId) { var localFolder = ApplicationData.Current.LocalFolder; await fileToCopy.CopyAsync(localFolder, pageId.ToString() + ".jpg"); await fileToCopy.CopyAsync(localFolder, pageId.ToString() + "_backup" + ".jpg"); }
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 { } }
/// <summary> /// On import-cert button clicked /// -- import Opcua server ceritifcate and save to local storage /// <summary> private async void btnImportCert_Button_Click(object sender, RoutedEventArgs e) { EnableSessionOpButtons(false); try { // import certificate var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; picker.FileTypeFilter.Add(".der"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); Windows.Storage.StorageFolder folder = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(m_cert_full_path); if (file != null) { Windows.Storage.StorageFile copiedFile = await file.CopyAsync(folder, file.Name, Windows.Storage.NameCollisionOption.ReplaceExisting); } } catch (Exception exception) { GuiUtils.HandleException(String.Empty, GuiUtils.CallerName(), exception); } EnableSessionOpButtons(true); }
public async void selectPic(Image pic) { var fop = new FileOpenPicker(); fop.ViewMode = PickerViewMode.Thumbnail; fop.SuggestedStartLocation = PickerLocationId.PicturesLibrary; fop.FileTypeFilter.Add(".jpg"); fop.FileTypeFilter.Add(".jpeg"); fop.FileTypeFilter.Add(".png"); fop.FileTypeFilter.Add(".gif"); Windows.Storage.StorageFile file = await fop.PickSingleFileAsync(); try { using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) { BitmapImage bitmapImage = new BitmapImage(); await bitmapImage.SetSourceAsync(fileStream); pic.Source = bitmapImage; imgName = file.Path.Substring(file.Path.LastIndexOf('\\') + 1); await file.CopyAsync(ApplicationData.Current.LocalFolder, imgName, NameCollisionOption.ReplaceExisting); Debug.WriteLine(imgName); } } catch (Exception) { return; } }
private async void ButtonAddPhoto_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(".jpeg"); picker.FileTypeFilter.Add(".png"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { if (!Directory.Exists(Path.Combine(ApplicationData.Current.TemporaryFolder.Path, "media"))) { Directory.CreateDirectory(Path.Combine(ApplicationData.Current.TemporaryFolder.Path, "media")); } // Application now has read/write access to the picked file if (!File.Exists(Path.Combine(ApplicationData.Current.TemporaryFolder.Path, "media", file.Name))) { await file.CopyAsync(await StorageFolder.GetFolderFromPathAsync(Path.Combine(ApplicationData.Current.TemporaryFolder.Path, "media"))); } MasterMenuItem.AddPhotoFile(new MediaFileViewModel() { FileName = Path.Combine(ApplicationData.Current.TemporaryFolder.Path, "media", file.Name) }); //PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Photos")); } else { } }
private async void ImportDatabase_Click(object sender, RoutedEventArgs e) { StorageFolder localFolder1 = ApplicationData.Current.LocalFolder; var picker = new Windows.Storage.Pickers.FileOpenPicker(); ///picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; picker.FileTypeFilter.Add(".db"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { try { string dbfile = "sdelkidatabase.db"; await file.CopyAsync(localFolder1, dbfile, NameCollisionOption.ReplaceExisting); StatusFile.Text = "Файл sdelkidatabase.db успешно скопирован (импортирован) в рабочую папку приложения."; } catch { StatusFile.Text = "Не удалось скопировать (импортировать) файл sdelkidatabase.db в рабочую папку приложения."; } } }
//图片选择 private async void barbutton_select_click(object sender, RoutedEventArgs e) { var filepicker = new Windows.Storage.Pickers.FileOpenPicker(); filepicker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; filepicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; filepicker.FileTypeFilter.Add(".jpg"); filepicker.FileTypeFilter.Add(".jpeg"); filepicker.FileTypeFilter.Add(".png"); Windows.Storage.StorageFile file = await filepicker.PickSingleFileAsync(); if (file != null) { await file.CopyAsync(ApplicationData.Current.LocalFolder, file.Name, NameCollisionOption.ReplaceExisting); imageuri = "ms-appdata:///local/" + file.Name; BitmapImage bitmapImage = new BitmapImage(new Uri(imageuri)); image.Source = bitmapImage; image_tem = bitmapImage;; ApplicationData.Current.LocalSettings.Values["newpage1_image"] = StorageApplicationPermissions.FutureAccessList.Add(file); } else { BitmapImage bitmapimage = new BitmapImage(new Uri("ms-appx:///Assets/bar.jpg")); image.Source = bitmapimage; image_tem = bitmapimage; imageuri = "ms-appx:///Assets/bar.jpg"; } }
private async void AddMusicButton_Click(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker { ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail, SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary }; picker.FileTypeFilter.Add(".mp3"); Windows.Storage.StorageFile musicfile = await picker.PickSingleFileAsync(); // Get the app's local folder to use as the destination folder. StorageFolder localFolder = ApplicationData.Current.LocalFolder; // Copy the file to the destination folder and rename it. // Replace the existing file if the file already exists. StorageFile copiedMusicFile = await musicfile.CopyAsync(localFolder, musicfile.Name, NameCollisionOption.ReplaceExisting); if (musicfile != null) { this.MusicPathString.Text = copiedMusicFile.Path;// Save musicfile path in the txt } else { this.MusicPathString.Text = "Operation cancelled"; } }
private async void Click_SelectPicture(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(".jpeg"); picker.FileTypeFilter.Add(".png"); picker.FileTypeFilter.Add(".gif"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; if (file == null) { return; } StorageFile fileCopy = await file.CopyAsync(localFolder, file.Name, NameCollisionOption.ReplaceExisting); string imgStr = "ms-appdata:///local/" + file.Name; Debug.WriteLine(imgStr); Img.Source = new BitmapImage(new Uri(imgStr)); }
private async void Imageoption_Checked(object sender, RoutedEventArgs e) { if (f == false) { Windows.Storage.ApplicationData.Current.LocalSettings.Values["CustomBackgroundBool"] = Imageoption.IsChecked; if ((string)Windows.Storage.ApplicationData.Current.LocalSettings.Values["CustomBackgroundPath"] == "") { 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(".jpeg"); picker.FileTypeFilter.Add(".png"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); StorageFile File = await file.CopyAsync(localFolder); BackGroundimage.Visibility = Visibility.Visible; BitmapImage bitmapImage = new BitmapImage(); // dimension, so long as one dimension measurement is provided bitmapImage.UriSource = new Uri(File.Path); BackGroundimage.Source = bitmapImage; Windows.Storage.ApplicationData.Current.LocalSettings.Values["CustomBackgroundPath"] = File.Path; int duration = 3000; try { TabViewPage.InAppNotificationMain.Show("Saved", duration); } catch { IncognitoTabView.InAppNotificationMain.Show("Saved", duration); } } catch { Windows.Storage.ApplicationData.Current.LocalSettings.Values["CustomBackgroundBool"] = false; int duration = 3000; try { TabViewPage.InAppNotificationMain.Show("Canceled", duration); } catch { IncognitoTabView.InAppNotificationMain.Show("Canceled", duration); } } } else { BackGroundimage.Visibility = Visibility.Collapsed; BitmapImage bitmapImage = new BitmapImage(); // dimension, so long as one dimension measurement is provided bitmapImage.UriSource = new Uri((string)Windows.Storage.ApplicationData.Current.LocalSettings.Values["CustomBackgroundPath"]); BackGroundimage.Source = bitmapImage; } } }
private async void SaveImageAsync(StorageFile file) { if (file != null) { StorageFile newImageFile = await file.CopyAsync(ApplicationData.Current.LocalFolder, Guid.NewGuid().ToString()); App.MainViewModel.SelectedBBQRecipe.ImagePath = newImageFile.Path; } }
private async void AddImageButton_Click(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker { ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail, SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary }; //picker.FileTypeFilter.Add(".jpg"); //picker.FileTypeFilter.Add(".jpeg"); picker.FileTypeFilter.Add(".png"); Windows.Storage.StorageFile imgfile = await picker.PickSingleFileAsync(); if (imgfile == null) { return; } // Get the app's local folder to use as the destination folder. StorageFolder localFolder = ApplicationData.Current.LocalFolder; // Copy the file to the destination folder and rename it. // Replace the existing file if the file already exists. StorageFile copiedImgFile = await imgfile.CopyAsync (localFolder, imgfile.Name, NameCollisionOption.ReplaceExisting); this.ImagePathString.Text = copiedImgFile.Name; BitmapImage image = new BitmapImage(); var storageFile = await StorageFile.GetFileFromPathAsync(copiedImgFile.Path); using (Windows.Storage.Streams.IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read)) { await image.SetSourceAsync(stream); } this.image.Source = image; _imgPath = copiedImgFile.Path; /* * if (imgfile != null) * { * this.ImagePathString.Text = copiedImgFile.Path; * this.image.Source = new BitmapImage(new Uri("ms-appx:///" + this.ImagePathString.Text)); * } * else * { * this.ImagePathString.Text = "Operation cancelled"; * } */ }
public static async Task<Note> CreateFromStorageFileAsync(StorageFile sf, NoteKind k, string name, string desc, string classId) { var docProps = await sf.Properties.GetDocumentPropertiesAsync(); var imgProps = await sf.Properties.GetImagePropertiesAsync(); imgProps.DateTaken = DateTime.Now; docProps.Title = name; docProps.Comment = desc; await docProps.SavePropertiesAsync(); await imgProps.SavePropertiesAsync(); var fileName = string.Format("{0}_{1}_{2}.{3}", classId, imgProps.DateTaken.ToString("MM-dd-yyyy ss-fff"), k.ToString().ToLower(), k == NoteKind.Txt ? "txt" : k == NoteKind.Img ? "jpg" : "mp4"); var newFile = await sf.CopyAsync(await ApplicationData.Current.RoamingFolder.CreateFolderAsync("Notes", CreationCollisionOption.OpenIfExists), fileName, NameCollisionOption.ReplaceExisting); return await CreateFromStorageFileAsync(newFile); }
public static async System.Threading.Tasks.Task <string> CacheFileAsync(string sourceFilePath) { string fileName = Path.GetFileName(sourceFilePath); Windows.Storage.StorageFile sourceStorageFile = Crosstales.FB.FileBrowserWSAImpl.LastOpenFile; Windows.Storage.StorageFolder cacheStorageFolder = Windows.Storage.ApplicationData.Current.LocalCacheFolder; var cacheStorageFile = await sourceStorageFile.CopyAsync(cacheStorageFolder, fileName, Windows.Storage.NameCollisionOption.ReplaceExisting); string cacheFilePath = cacheStorageFile.Path; return(cacheFilePath); }
public static IAsyncOperation <StorageFile> CopyOrReplaceAsync(this StorageFile storageFile, StorageFolder destinationFolder) { if (storageFile == null) { throw new ArgumentNullException(nameof(storageFile)); } if (destinationFolder == null) { throw new ArgumentNullException(nameof(destinationFolder)); } return(storageFile.CopyAsync(destinationFolder, storageFile.Name, NameCollisionOption.ReplaceExisting)); }
private async void FileButton_Click(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; picker.FileTypeFilter.Add(".csv"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { StorageFolder folder = ApplicationData.Current.TemporaryFolder; var copiedFile = await file.CopyAsync(folder, file.Name, NameCollisionOption.ReplaceExisting); var r = await DataSourceModel.ReadFileForDrawItem(copiedFile); if (r != null) { if (r.ItemList.Count > 200 || r.ItemList.Count == 0) { ContentDialog dialog = new ContentDialog(); dialog.Title = Strings.Resources.DataSetting_Dialog_Error; dialog.Content = Strings.Resources.DataSetting_Dialog_Exceed; dialog.PrimaryButtonText = Strings.Resources.DataSetting_Dialog_Ok; await dialog.ShowAsync(); } else { this.FilePathText.Text = copiedFile.Name; ApplyDataSource(); return; } } else { ContentDialog dialog = new ContentDialog(); dialog.Title = Strings.Resources.DataSetting_Dialog_Error; dialog.Content = Strings.Resources.DataSetting_Dialog_FileError; dialog.PrimaryButtonText = Strings.Resources.DataSetting_Dialog_Ok; await dialog.ShowAsync(); } SetDataModel(); } }
private async void ImageButton_Click(object sender, RoutedEventArgs e) { //Get File var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; picker.FileTypeFilter.Add(".png"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { await file.CopyAsync(Globals.storageLocation, Globals.currentProject + ".png", NameCollisionOption.ReplaceExisting); //Add image data to Project Data. foreach (var p in Globals.projects) { int c = 0; if (p.projectName == Globals.currentProject) { Globals.projects[c].imgSource = Globals.storageLocation.Path + "\\" + Globals.currentProject + ".png"; //Save Data To File Globals.SaveProjecList(); //Load Path & Image ImageFileBlock.Text = Globals.projects[c].imgSource.Substring(p.imgSource.LastIndexOf("\\") + 1); StorageFile imageFile = await StorageFile.GetFileFromPathAsync(p.imgSource); using (var stream = await imageFile.OpenAsync(FileAccessMode.Read)) { var img = new BitmapImage(); img.SetSource(stream); ImageCanvas.Source = img; ImageCanvas.Stretch = Stretch.None; ImageCanvas.Height = 100; ImageCanvas.Width = 75; ImageCanvas.Opacity = .75; ImageCanvas.VerticalAlignment = VerticalAlignment.Top; ImageCanvas.HorizontalAlignment = HorizontalAlignment.Center; } } c++; } } }
private async void AddMusicButton_Click(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker { ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail, SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary }; picker.FileTypeFilter.Add(".mp3"); Windows.Storage.StorageFile musicfile = await picker.PickSingleFileAsync(); if (musicfile != null) { // Save musicfile path in the txt // Get the app's local folder to use as the destination folder. StorageFolder localFolder = ApplicationData.Current.LocalFolder; // Copy the file to the destination folder and rename it. // Replace the existing file if the file already exists. StorageFile copiedMusicFile = await musicfile.CopyAsync(localFolder, musicfile.Name, NameCollisionOption.ReplaceExisting); this.MusicPathString.Text = copiedMusicFile.Name; FileStream fs = new FileStream(copiedMusicFile.Path, FileMode.Open, FileAccess.Read, FileShare.Read); // MP3MetafileReader(fs); _mp3Path = copiedMusicFile.Path; _mp3Title = copiedMusicFile.Name; } /* * // Get the app's local folder to use as the destination folder. * StorageFolder localFolder = ApplicationData.Current.LocalFolder; * // Copy the file to the destination folder and rename it. * // Replace the existing file if the file already exists. * StorageFile copiedMusicFile = await musicfile.CopyAsync(localFolder, musicfile.Name, NameCollisionOption.ReplaceExisting); * * /* * if (musicfile != null) * { * this.MusicPathString.Text = copiedMusicFile.Path;// Save musicfile path in the txt * } * else * { * this.MusicPathString.Text = "Operation cancelled"; * } */ }
private async void CopyFile_OnClick(object sender, RoutedEventArgs e) { if (listBox.SelectedItem == null) { return; } ListBoxItem item = (ListBoxItem)listBox.SelectedItem; if (item.Tag is Windows.Storage.StorageFile) { Windows.Storage.StorageFile file = (Windows.Storage.StorageFile)item.Tag; await file.CopyAsync(currentFolder, fileName.Text); } ScanDir(currentFolder); }
/// <summary> /// Launches the file picker and allows the user to pick an image from their pictures library.<br/> /// The image will then be used as the background image in the main launcher page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void imageButton_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; //Standard Image Support picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".jpeg"); picker.FileTypeFilter.Add(".png"); picker.FileTypeFilter.Add(".svg"); //GIF Support picker.FileTypeFilter.Add(".gif"); picker.FileTypeFilter.Add(".gifv"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { // Application now has read/write access to the picked file Debug.WriteLine("Picked photo: " + file.Name); var backgroundImageFolder = await localFolder.CreateFolderAsync("backgroundImage", CreationCollisionOption.OpenIfExists); if ((string)App.localSettings.Values["bgImageAvailable"] == "1") { var filesInFolder = await backgroundImageFolder.GetFilesAsync(); if (filesInFolder.Count > 0) { foreach (var photo in filesInFolder) { await photo.DeleteAsync(); } } } StorageFile savedImage = await file.CopyAsync(backgroundImageFolder); App.localSettings.Values["bgImageAvailable"] = "1"; } else { Debug.WriteLine("Operation cancelled."); } }
private async void ButtonLogo_Click(object sender, RoutedEventArgs e) { StorageFolder localFolder1 = ApplicationData.Current.LocalFolder; //Путь доступа к папке ms-appdata:///local/ var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; picker.FileTypeFilter.Add(".jpeg"); picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".png"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); //string DelFile = Logofilename; if (file != null) { try { string dbfile = file.Name.ToString(); await file.CopyAsync(localFolder1, dbfile, NameCollisionOption.ReplaceExisting); Logofilename = dbfile; Image img = new Image(); BitmapImage bitmapImage = new BitmapImage(); bitmapImage.UriSource = new Uri("ms-appdata:///local/" + dbfile); ImageLogo.Source = bitmapImage; // if (DelFile != Logofilename) //удаляем старый файл изображения логотипа // { // try { StorageFile DFile = await localFolder1.GetFileAsync(DelFile); await DFile.DeleteAsync(); } // catch { } // } TextBlockStatusFile5.Text = "Файл логотипа " + dbfile + " успешно скопирован (импортирован) в рабочую папку приложения."; } catch { TextBlockStatusFile5.Text = "Не удалось скопировать файл логотипа в рабочую папку приложения."; } } }
// http://stackoverflow.com/questions/36728529/extracting-specific-file-from-archive-in-uwp private async Task UnzipKmz(StorageFile kmzFile) { StorageFolder folder = ApplicationData.Current.TemporaryFolder; // Clear in temporary folder ClearTempFolder(); // Need to copy file to temporary folder StorageFile temp = await kmzFile.CopyAsync(folder); using (ZipArchive archive = ZipFile.OpenRead(temp.Path)) { foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.FullName.ToString() == "doc.kml") { entry.ExtractToFile(Path.Combine(folder.Path, entry.FullName)); // Set KML file kmlFile = await folder.GetFileAsync("doc.kml"); } } } }
public static async Task resetFolders() { Windows.Storage.StorageFolder localfolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile firstfile = await localfolder.GetFileAsync("firsttime"); await firstfile.DeleteAsync(); var folders = await localfolder.GetFoldersAsync(); foreach (Windows.Storage.StorageFolder folder in folders) { await folder.DeleteAsync(); } Windows.Storage.StorageFolder stor = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("thumbs", Windows.Storage.CreationCollisionOption.FailIfExists); Uri uri = new Uri("ms-appx:///Assets/bookImage.jpg"); Windows.Storage.StorageFile file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri); Windows.Storage.StorageFolder imageFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFolderAsync("thumbs"); await file.CopyAsync(imageFolder, "default.jpg"); }
private async void ExecuteSavePictureCommand(StorageFile file) { try { if (file != null) { // Copy the file into local folder await file.CopyAsync(ApplicationData.Current.LocalFolder, file.Name, NameCollisionOption.GenerateUniqueName); // Save in the ToDoItem TodoItem.ImageUri = new Uri("ms-appdata:///local/" + file.Name); } } finally { Busy = false; } }
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; }
//------------------------------------------------------------------------------- #region +[static]CopyToLocal ローカルにチェックリストを保存 //------------------------------------------------------------------------------- // public static async Task CopyToLocal(StorageFile file) { var localDir = Windows.Storage.ApplicationData.Current.LocalFolder; await file.CopyAsync(localDir, CHECKLIST_LOCAL_FILENAME, NameCollisionOption.ReplaceExisting); }
public static async Task<StorageFile> SaveFiletoLocalAsync(StorageFile file, string desiredName) { var local = ApplicationData.Current.LocalFolder; try { return await file.CopyAsync(local, desiredName + file.FileType, NameCollisionOption.ReplaceExisting); } catch (Exception) { return null; } }
private async void AppBarButton_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(".txt"); picker.FileTypeFilter.Add(".dat"); picker.FileTypeFilter.Add(".rtf"); picker.FileTypeFilter.Add(".db"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { // Application now has read/write access to the picked file this.nameFile.Text = "Имя файла: " + file.Name; Debug.WriteLine(file.FileType); string err = String.Empty; char[] rowSplitter = { '\r', '\n' }; if (file.FileType != ".db") { string[] text = (await Windows.Storage.FileIO.ReadTextAsync(file)).Split(rowSplitter, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < text.Length; i++) { string[] text1 = text[i].Split('\t'); try { if (text1[3] == String.Empty || text1[3] == null || text1[4] == String.Empty || text1[4] == null || text1[1].Split('_')[1] == "Test") { } else { DataColecF.Add(new ClassFileLT() { nomer = Convert.ToInt32(text1[0]), nameFile = text1[1], TimeOpen = text1[3], TimeClose = text1[4], nameRun = text1[5] }); } } catch (Exception ex) { MessageDialog messageDialog = new MessageDialog(ex.ToString()); await messageDialog.ShowAsync(); } } } else { try { StorageFile storageFile = await file.CopyAsync(ApplicationData.Current.LocalFolder, file.Name, NameCollisionOption.ReplaceExisting); //SqliteConnection db = new SqliteConnection("Data Source = " + file.Path); openBDTime(file); string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, file.Name); // StorageFile storageFile = await StorageFile.GetFileFromPathAsync(dbpath); // await storageFile.DeleteAsync(); } catch (Exception ex) { MessageDialog messageDialog = new MessageDialog(ex.Message); await messageDialog.ShowAsync(); } } } else { this.nameFile.Text = "Файл не выбран"; } }
private async void Button_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(".jpeg"); picker.FileTypeFilter.Add(".png"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { string username = readSetting("userName"); Debug.WriteLine(file.Name); //Image img1 = new BitmapImage(file.Name); StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; /* Debug.WriteLine(localFolder.Path + "10000000");*/ StorageFile copiedFile = await file.CopyAsync(localFolder, file.Name, NameCollisionOption.ReplaceExisting);//copy to localstate lst.Add(new MovieData { Title = copiedFile.Name, ImageData = LoadImage("ms-appdata:///local/" + copiedFile.Name) }); //BitmapImage img = LoadImage(copiedFile.Path); /* Windows.Storage.Streams.IRandomAccessStream random = await Windows.Storage.Streams.RandomAccessStreamReference.CreateFromUri(new Uri("ms-appdata:///local/" + copiedFile.Name)).OpenReadAsync();//ms-appdata:///local/ * Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(random);*/ // var stream = File.Open( copiedFile.Path, FileMode.Open); // Construct FirebaseStorage with path to where you want to upload the file and put it there /* var task = new FirebaseStorage("gs://photogallery-81868.appspot.com/") * .Child("data") * .Child("random") * .Child("copiedFile.Name") * .PutAsync(stream); * * // Track progress of the upload * task.Progress.ProgressChanged += (s, y) => Debug.WriteLine($"Progress: {y.Percentage} %"); * * // Await the task to wait until upload is completed and get the download url * var downloadUrl = await task;*/ /* Windows.Graphics.Imaging.PixelDataProvider pixelData = await decoder.GetPixelDataAsync(); * byte[] bytes = pixelData.DetachPixelData(); * string output = Convert.ToBase64String(bytes); * DateTime dd = DateTime.Now; * var data = new Image_Model * { * * Img = output, * Title = file.Name, * DateAdded = dd.ToString("dd/MM/yyyy") * }; * SetResponse request = await client.SetTaskAsync("Image/"+username+"/", data); * Image_Model result = request.ResultAs<Image_Model>(); * Debug.WriteLine("Success");*/ // LoadImages(); //var x = Database.InsertImage(copiedFile.Name, img); //lst = Database.GetAllImages(); //Debug.WriteLine(x); } else { } //lst.Add(new MovieData { Title = "Movie 100", ImageData = LoadImage("StoreLogo.png") }); //LoadImages(); }
public static async Task<Uri> SaveFiletoLocalAsync(string path, StorageFile file, string desiredName) { var local = ApplicationData.Current.LocalFolder; try { var folder = await local.CreateFolderAsync(path, CreationCollisionOption.OpenIfExists); await file.CopyAsync(folder, desiredName + file.FileType, NameCollisionOption.ReplaceExisting); return new Uri("ms-appdata:///local/" + path.Replace("\\", "/") + '/' + desiredName + file.FileType); } catch (Exception) { return null; } }
private async Task<string> imgfolder(file_storage temp, StorageFile file) //StorageFile file) { //string str = _file.Name; //StorageFolder image = null; //try //{ // image = await _folder.GetFolderAsync(str); //} //catch //{ //} //if (image == null) //{ // image = await _folder.CreateFolderAsync(str, CreationCollisionOption.OpenIfExists); //} string str; file = await file.CopyAsync(temp.folder, file.Name, NameCollisionOption.GenerateUniqueName); if ((file.FileType == ".png") || (file.FileType == ".jpg") || (file.FileType == ".gif")) { str = $"![这里写图片描述]({temp.folder}/{file.Name})\n\n"; return str; } str = $"[{file.Name}]({temp.folder}/{file.Name})\n\n"; return str; }
public async Task SetImageSource(StorageFile sourceFile) { var tempFolder = ApplicationData.Current.TemporaryFolder; m_ext = sourceFile.Name.Substring(sourceFile.Name.LastIndexOf('.')); // original full size image //var img = await sourceFile.CopyAsync(tempFolder, m_filename + "a" + m_ext, NameCollisionOption.ReplaceExisting); // cropped image will be stored here //img = await sourceFile.CopyAsync(tempFolder, m_filename + m_ext, NameCollisionOption.ReplaceExisting); //ImageSource = img.Path; var f = tempFolder.Path + "\\"; var i1 = m_filename + "a" + m_ext; var i2 = m_filename + m_ext; // copy new source to temp folder await sourceFile.CopyAsync(tempFolder, i1, NameCollisionOption.ReplaceExisting); // crop image to target size await Common.CropHelper.CropImageAsync(f + i1, f + i2, 1, new Rect(0, 0, ImageWidth, ImageHeight), Common.CropType.GetLargestRect); ImageSource = CreateSource(f + i2); }
private async void FileOpenPicker_Continuation(StorageFile file) { if (file != null) { var destFile = await file.CopyAsync(Windows.Storage.ApplicationData.Current.LocalFolder, file.Name, NameCollisionOption.ReplaceExisting); var userPhoto = new UserPhotoDataItem() { Title = destFile.Name}; userPhoto.SetImage(destFile.Path); item.UserPhotos.Add(userPhoto); } }
private async void ChooseBackgroundImage(StorageFile file) { String filename = "menuBackground.png"; await file.CopyAsync(ApplicationData.Current.LocalFolder as IStorageFolder, filename, NameCollisionOption.ReplaceExisting); AppSettings.BackgroundImage = filename; LoadBackgroundImage(); }
/// <summary> /// Copies the user's avatar's file to it's place (avatars subfolder). /// </summary> /// <param name="file">The user's avatar's file.</param> /// <returns>The copy of the file.</returns> private async Task<StorageFile> SaveUserAvatarFile(StorageFile file) { var copy = await file.CopyAsync(_avatarsFolder); await copy.RenameAsync(ToxModel.Instance.Id.PublicKey + ".png", NameCollisionOption.ReplaceExisting); return copy; }
private async void Click_SelectPicture(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(".jpeg"); picker.FileTypeFilter.Add(".png"); picker.FileTypeFilter.Add(".gif"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; if (file == null) { return; } try { string myFileName = DateTime.Now.ToString("yyyyMMddHHmmss_") + (new Random()).Next() + file.FileType; StorageFile fileCopy = await file.CopyAsync(localFolder, myFileName, NameCollisionOption.ReplaceExisting); string imgStr = "ms-appdata:///local/" + myFileName; Debug.WriteLine(imgStr); Img.Source = new BitmapImage(new Uri(imgStr)); } catch (Exception error) { var box1 = new MessageDialog("Oops! Something Went Wrong!\n\n" + error.ToString()).ShowAsync(); } /* * if (file != null) * { * var inputFile = SharedStorageAccessManager.AddFile(file); * var destination = await ApplicationData.Current.LocalFolder.CreateFileAsync("Cropped.jpg", CreationCollisionOption.ReplaceExisting); * var destinationFile = SharedStorageAccessManager.AddFile(destination); * var options = new LauncherOptions(); * options.TargetApplicationPackageFamilyName = "Microsoft.Windows.Photos_8wekyb3d8bbwe"; * * var parameters = new ValueSet(); * parameters.Add("InputToken", inputFile); * parameters.Add("DestinationToken", destinationFile); * parameters.Add("ShowCamera", false); * parameters.Add("CropWidthPixals", 280); * parameters.Add("CropHeightPixals", 300); * * var result = await Launcher.LaunchUriForResultsAsync(new Uri("microsoft.windows.photos.crop:"), options, parameters); * * if (result.Status == LaunchUriStatus.Success && result.Result != null) * { * try * { * var stream = await destination.OpenReadAsync(); * var bitmap = new BitmapImage(); * await bitmap.SetSourceAsync(stream); * * Img.Source = bitmap; * Debug.WriteLine(((BitmapImage)Img.Source).UriSource.ToString()); * } * catch (Exception ex) * { * Debug.WriteLine(ex.Message + ex.StackTrace); * } * } * }*/ }
/// <summary> /// Copies a file to the first folder on a storage. /// </summary> /// <param name="sourceFile"></param> /// <param name="storage"></param> async private Task CopyFileToFolderOnStorageAsync(StorageFile sourceFile, StorageFolder storage) { var storageName = storage.Name; // Construct a folder search to find sub-folders under the current storage. // The default (shallow) query should be sufficient in finding the first level of sub-folders. // If the first level of sub-folders are not writable, a deep query + recursive copy may be needed. var folders = await storage.GetFoldersAsync(); if (folders.Count > 0) { var destinationFolder = folders[0]; var destinationFolderName = destinationFolder.Name; rootPage.NotifyUser("Trying the first sub-folder: " + destinationFolderName + "...", NotifyType.StatusMessage); try { var newFile = await sourceFile.CopyAsync(destinationFolder, sourceFile.Name, NameCollisionOption.GenerateUniqueName); rootPage.NotifyUser("Image " + newFile.Name + " created in folder: " + destinationFolderName + " on " + storageName, NotifyType.StatusMessage); } catch (Exception e) { rootPage.NotifyUser("Failed to copy image to the first sub-folder: " + destinationFolderName + ", " + storageName + " may not allow sending files to its top level folders. Error: " + e.Message, NotifyType.ErrorMessage); } } else { rootPage.NotifyUser("No sub-folders found on " + storageName + " to copy to", NotifyType.StatusMessage); } }
public async Task SaveBitmapToPictureLibrary(StorageFile image) { await image.CopyAsync(KnownFolders.PicturesLibrary); }
public async Task<string> imgfolder(StorageFile file) { string str = "image"; StorageFolder image = null; try { image = await _folder.GetFolderAsync(str); } catch { } if (image == null) { image = await _folder.CreateFolderAsync(str, CreationCollisionOption.OpenIfExists); } file = await file.CopyAsync(image, file.Name, NameCollisionOption.GenerateUniqueName); if ((file.FileType == ".png") || (file.FileType == ".jpg")) { str = $"![这里写图片描述](image/{file.Name})\r\n\r\n"; return str; } else { str = $"[{file.Name}](image/{file.Name})\r\n\r\n"; return str; } }
public static async void SetPictureFile(StorageFile file) { // Delete the old picture. if (_pictureFile != null) { await _pictureFile.DeleteAsync(); await file.CopyAsync(ApplicationData.Current.LocalFolder); _pictureFile = file; } else { // Check if the file actually does exist. try { StorageFile possibleFile = await ApplicationData.Current.LocalFolder.GetFileAsync(file.Name); } catch (Exception) { file.CopyAsync(ApplicationData.Current.LocalFolder); _pictureFile = file; } } }
private async void LoadKeeButton_Click(object sender, RoutedEventArgs e) { try { List <KeepassClass> PassList = new List <KeepassClass>(); var dbpath = ""; var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; picker.FileTypeFilter.Add(".kdb"); picker.FileTypeFilter.Add(".kdbx"); Windows.Storage.StorageFile File = await picker.PickSingleFileAsync(); StorageFolder folder = Windows.Storage.ApplicationData.Current.LocalFolder; StorageFile file = await File.CopyAsync(folder); if (file != null) { dbpath = file.Path; } var masterpw = MasterPassword.Password; var ioConnInfo = new IOConnectionInfo { Path = file.Path }; var compKey = new CompositeKey(); compKey.AddUserKey(new KcpPassword(MasterPassword.Password)); var db = new KeePassLib.PwDatabase(); Windows.Storage.ApplicationData.Current.LocalSettings.Values["KeepassLocalFilePathBool"] = true; Windows.Storage.ApplicationData.Current.LocalSettings.Values["KeepassLocalFilePath"] = file.Name; /* var kdbx = new KdbxFile(db); * using (var fs = await file.OpenReadAsync()) * { * await Task.Run(() => * { * kdbx.Load(file.Path, KdbxFormat.Default, null); * }); * * // return new KdbxDatabase(dbFile, db, dbFile.IdFromPath()); * }*/ db.Open(ioConnInfo, compKey, null); var kpdata = from entry in db.RootGroup.GetEntries(true) select new { Group = entry.ParentGroup.Name, Title = entry.Strings.ReadSafe("Title"), Username = entry.Strings.ReadSafe("UserName"), Password = entry.Strings.ReadSafe("Password"), URL = entry.Strings.ReadSafe("URL"), Notes = entry.Strings.ReadSafe("Notes") }; foreach (var Item in kpdata) { PassList.Add(new KeepassClass() { Title = Item.Title, Website = Item.URL, Password = Item.Password, User = Item.Username }); } PassListView.ItemsSource = PassList; LoadKeeButton.Visibility = Visibility.Collapsed; AddKeeButton.Visibility = Visibility.Visible; EnterKeeButton.Visibility = Visibility.Visible; db.Close(); } catch { int duration = 3000; try { TabViewPage.InAppNotificationMain.Show("Wrong password!", duration); } catch { IncognitoTabView.InAppNotificationMain.Show("Wrong password!", duration); } Windows.Storage.ApplicationData.Current.LocalSettings.Values["KeepassLocalFilePathBool"] = false; Windows.Storage.ApplicationData.Current.LocalSettings.Values["KeepassLocalFilePath"] = null; } }