Exemple #1
0
        public static string GetInitialDirectory(PickerLocationId location)
        {
            switch (location)
            {
            case PickerLocationId.DocumentsLibrary:
                return(GetFolderPath(SpecialFolder.MyDocuments));

            case PickerLocationId.ComputerFolder:
                return(@"/");

            case PickerLocationId.Desktop:
                return(GetFolderPath(SpecialFolder.Desktop));

            case PickerLocationId.MusicLibrary:
                return(GetFolderPath(SpecialFolder.MyMusic));

            case PickerLocationId.PicturesLibrary:
                return(GetFolderPath(SpecialFolder.MyPictures));

            case PickerLocationId.VideosLibrary:
                return(GetFolderPath(SpecialFolder.MyVideos));

            default:
                return(string.Empty);
            }
        }
        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;
        }
Exemple #3
0
        public static async Task <StorageFile> OpenFilePicker(string tokenName, PickerLocationId location, params string[] fileTypes)
        {
            try
            {
                var filePicker = new FileOpenPicker();
                filePicker.SuggestedStartLocation = location;
                foreach (var type in fileTypes)
                {
                    filePicker.FileTypeFilter.Add(type);
                }
                var filePick = await filePicker.PickSingleFileAsync();

                if (filePick != null)
                {
                    Windows.Storage.AccessCache.StorageApplicationPermissions.
                    FutureAccessList.AddOrReplace(tokenName, filePick);
                    return(filePick);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                ThrowUnHandleException(ex);
                await UIHelper.ShowMessageDialog("Unable to open the specified file.");

                return(null);
            }
        }
Exemple #4
0
        private async Task <StorageFile> LoadFile(PickerLocationId locationId)
        {
            FileOpenPicker openPicker = new FileOpenPicker();

            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.ViewMode = PickerViewMode.Thumbnail;

            // Filter to include a sample subset of file types.
            openPicker.FileTypeFilter.Clear();
            if (locationId == PickerLocationId.PicturesLibrary)
            {
                openPicker.FileTypeFilter.Add(".jpeg");
                openPicker.FileTypeFilter.Add(".jpg");
            }
            else if (locationId == PickerLocationId.VideosLibrary)
            {
                openPicker.FileTypeFilter.Add(".mov");
                openPicker.FileTypeFilter.Add(".mp4");
            }

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

            return(file);
        }
Exemple #5
0
        public static async Task <StorageFile> DisplaySingleFilePicker(
            PickerViewMode viewMode         = PickerViewMode.List,
            PickerLocationId preferLocation = PickerLocationId.Desktop,
            List <string> filters           = null)
        {
            var filePicker = new FileOpenPicker {
                ViewMode = viewMode,
                SuggestedStartLocation = preferLocation
            };

            if (filters is null)
            {
                filters = new List <string> {
                    "*"
                };
            }
            foreach (var filter in filters)
            {
                filePicker.FileTypeFilter.Add(filter);
            }

            StorageFile file = await filePicker.PickSingleFileAsync();

            return(file);
        }
Exemple #6
0
        /// <summary>
        /// The file picker is displayed so that the user can select a file.
        /// Then copy to the temporary folder, and return the copy.
        /// </summary>
        /// <param name="location"> The destination locationId. </param>
        /// <returns> The product file. </returns>
        public async static Task <StorageFile> PickAndCopySingleImageFileAsync(PickerLocationId location)
        {
            //Picker
            FileOpenPicker openPicker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = location,
                FileTypeFilter         =
                {
                    ".jpg",
                    ".jpeg",
                    ".png",
                    ".bmp"
                }
            };

            //File
            StorageFile file = await openPicker.PickSingleFileAsync();

            if (file == null)
            {
                return(null);
            }

            StorageFile copyFile = await file.CopyAsync(ApplicationData.Current.TemporaryFolder, file.Name, NameCollisionOption.ReplaceExisting);

            return(copyFile);
        }
Exemple #7
0
        static async Task <FileInfo[]> DoPickAsset(PickerLocationId location, string[] extensions, bool enableMultipleSelection)
        {
            var picker = new FileOpenPicker
            {
                SuggestedStartLocation = location,
                ViewMode = PickerViewMode.Thumbnail
            };

            picker.FileTypeFilter.AddRange(extensions);

            if (enableMultipleSelection)
            {
                var files = await picker.PickMultipleFilesAsync().AsTask();

                var result = new List <FileInfo>();
                foreach (var item in files.ToList())
                {
                    result.Add(await item.SaveToTempFile());
                }
                return(result.ToArray());
            }

            var picked = await picker.PickSingleFileAsync();

            return(new[] { await picked.SaveToTempFile() });
        }
Exemple #8
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;
        }
        /// <summary>
        /// Translate picker to location
        /// </summary>
        /// <param name="locationId">location</param>
        /// <returns></returns>
        public string Translate(PickerLocationId locationId)
        {
            switch (locationId)
            {
                case PickerLocationId.ComputerFolder:
                    return Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
                    break;
                case PickerLocationId.Desktop:
                    return Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                    break;
                case PickerLocationId.DocumentsLibrary:
                    return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    break;
                case PickerLocationId.Downloads:
                    string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
                    return Path.Combine(pathUser, "Downloads");
                    break;
                case PickerLocationId.HomeGroup:
                    break;
                case PickerLocationId.MusicLibrary:
                    return Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
                    break;
                case PickerLocationId.PicturesLibrary:
                    return Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
                    break;
                case PickerLocationId.VideosLibrary:
                    return Environment.GetFolderPath(Environment.SpecialFolder.MyVideos);
                    break;
            }

            return null;
        }
Exemple #10
0
        public async Task <Response <StorageFile> > SaveInkToInkFile(PickerLocationId location)
        {
            var picker = new FileSavePicker
            {
                SuggestedStartLocation = location
            };

            picker.FileTypeChoices.Add("INK files", new List <string> {
                ".ink"
            });
            var file = await picker.PickSaveFileAsync();

            if (file == null)
            {
                return(new Response <StorageFile>
                {
                    IsSuccess = false,
                    Message = $"{nameof(file)} is null",
                    Item = null
                });
            }
            var response = await SaveToStorageFile(InkCanvas, file);

            return(new Response <StorageFile>
            {
                IsSuccess = response.IsSuccess,
                Message = response.Message,
                Item = file
            });
        }
        public async static Task <StorageFile> PickFiles(List <string> fileTypes,
                                                         string metaData = "New Storage Item",
                                                         PickerViewMode pickerViewMode     = PickerViewMode.Thumbnail,
                                                         PickerLocationId pickerLocationId = PickerLocationId.PicturesLibrary)
        {
            var picker = new FileOpenPicker();

            picker.ViewMode = pickerViewMode;
            picker.SuggestedStartLocation = pickerLocationId;

            foreach (string type in fileTypes)
            {
                picker.FileTypeFilter.Add(type);
            }

            StorageFile file = await picker.PickSingleFileAsync();

            if (file != null)
            {
                // Application now has read/write access to the picked file
                return(file);
            }

            Console.WriteLine("Operation cancelled.");
            return(null);
        }
Exemple #12
0
        public static async Task <StorageFile> OpenData(PickerLocationId dir, FileTypes[] ft)
        {
            if (dir == null)
            {
                dir = PickerLocationId.Unspecified;
            }

            FileOpenPicker openPicker = new FileOpenPicker();

            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = dir;

            for (int i = 0; i < ft.Length; i++)
            {
                openPicker.FileTypeFilter.Add(ft[i].FileExtension);
            }

            StorageFile file = await openPicker.PickSingleFileAsync();

            if (file != null)
            {
                return(file);
            }

            return(null);
        }
Exemple #13
0
        static FileOpenPicker CreatePicker(PickerLocationId p_locationstring, string[] p_allowedTypes)
        {
            var picker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.List,
                SuggestedStartLocation = p_locationstring,
            };

            var hasAtleastOneType = false;

            if (p_allowedTypes != null)
            {
                foreach (var type in p_allowedTypes)
                {
                    if (type.StartsWith("."))
                    {
                        picker.FileTypeFilter.Add(type);
                        hasAtleastOneType = true;
                    }
                }
            }
            if (!hasAtleastOneType)
            {
                picker.FileTypeFilter.Add("*");
            }
            return(picker);
        }
        /// <summary>
        /// New from Picture.
        /// </summary>
        /// <param name="location"> The picker locationId. </param>
        public async Task NewFromPicture(PickerLocationId location)
        {
            StorageFile file = await FileUtil.PickSingleImageFileAsync(location);

            StorageFile copyFile = await FileUtil.CopySingleImageFileAsync(file);

            await this.NewFromPictureCore(copyFile);
        }
        public static FileOpenPicker GetFileOpenPicker(List <string> fileTypes, PickerLocationId locationId = PickerLocationId.DocumentsLibrary, PickerViewMode viewMode = PickerViewMode.Thumbnail)
        {
            FileOpenPicker fileOpenPicker = new FileOpenPicker
            {
                SuggestedStartLocation = locationId,
                ViewMode = viewMode
            };

            fileTypes.ForEach((fileType) => fileOpenPicker.FileTypeFilter.Add(fileType));
            return(fileOpenPicker);
        }
 /// <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);
 }
Exemple #17
0
        public static async Task <StorageFolder> OpenFolder(PickerLocationId locationId, string[] fileExtensions)
        {
            FolderPicker folderPicker = new FolderPicker()
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = locationId
            };

            var folder = await folderPicker.PickSingleFolderAsync();

            return(folder);
        }
Exemple #18
0
        public static async Task SaveData(object data, PickerLocationId dir, FileTypes[] ft, string SuggestedName)
        {
            if (dir == null)
            {
                dir = PickerLocationId.Unspecified;
            }
            FileSavePicker savePicker = new FileSavePicker();

            savePicker.SuggestedStartLocation = dir;

            if (ft == null || ft.Length == 0)
            {
                return;
            }

            for (int i = 0; i < ft.Length; i++)
            {
                savePicker.FileTypeChoices.Add(ft[i].FileName, new List <string>()
                {
                    ft[i].FileExtension
                });
            }

            savePicker.SuggestedFileName = SuggestedName;

            StorageFile file = await savePicker.PickSaveFileAsync();

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

                if (data is WriteableBitmap)
                {
                    await WriteImage(file, (WriteableBitmap)data);
                }



                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                if (status == FileUpdateStatus.Complete)
                {
                    System.Diagnostics.Debug.Write("File " + file.Name + " was saved.");
                }
                else
                {
                    System.Diagnostics.Debug.Write("File " + file.Name + " couldn't be saved.");
                }
            }
        }
Exemple #19
0
        public async Task <bool> SaveInkToGif(PickerLocationId location)
        {
            IReadOnlyList <InkStroke> currentStrokes = InkCanvas.InkPresenter.StrokeContainer.GetStrokes();

            // Strokes present on ink canvas.
            if (currentStrokes.Count > 0)
            {
                FileSavePicker savePicker =
                    new FileSavePicker {
                    SuggestedStartLocation = location
                };
                savePicker.FileTypeChoices.Add(
                    "GIF with embedded ISF",
                    new List <string> {
                    ".gif"
                });
                savePicker.DefaultFileExtension = ".gif";
                savePicker.SuggestedFileName    = "Tracing-ISF-Gif";

                // Show the file picker.
                StorageFile file = await savePicker.PickSaveFileAsync();

                // When chosen, picker returns a reference to the selected file.
                if (file != null)
                {
                    CachedFileManager.DeferUpdates(file);
                    IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite);

                    using (IOutputStream outputStream = stream.GetOutputStreamAt(0))
                    {
                        await InkCanvas.InkPresenter.StrokeContainer.SaveAsync(outputStream);

                        await outputStream.FlushAsync();
                    }
                    stream.Dispose();

                    FileUpdateStatus status =
                        await CachedFileManager.CompleteUpdatesAsync(file);

                    if (status == FileUpdateStatus.Complete)
                    {
                        return(true);
                    }
                    return(false);
                }
                return(false);
            }
            return(false);
        }
Exemple #20
0
        /// <summary>
        /// Load strokes from .ink file to InkCanvas
        /// </summary>
        /// <param name="inkCanvas">InkCanvas Object</param>
        /// <param name="location">PickerLocationId</param>
        /// <returns>Task</returns>
        public static async Task LoadInkFile(InkCanvas inkCanvas, PickerLocationId location)
        {
            var picker = new FileOpenPicker
            {
                SuggestedStartLocation = location
            };

            picker.FileTypeFilter.Add(".ink");
            var pickedFile = await picker.PickSingleFileAsync();

            if (pickedFile != null)
            {
                await LoadInkFile(inkCanvas, pickedFile);
            }
        }
Exemple #21
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);

                    await encoder.BitmapContainerProperties.SetPropertiesAsync(new BitmapPropertySet
                    {
                        {
                            "System.Comment",
                            new BitmapTypedValue("Exported via Character Map UWP", Windows.Foundation.PropertyType.String)
                        }
                    });

                    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);
        }
Exemple #22
0
        public static async Task <StorageFolder> DisplayFolderPicker(
            PickerViewMode viewMode         = PickerViewMode.List,
            PickerLocationId preferLocation = PickerLocationId.Desktop)
        {
            var folderPicker = new FolderPicker()
            {
                ViewMode = viewMode,
                SuggestedStartLocation = preferLocation
            };

            folderPicker.FileTypeFilter.Add("*");

            StorageFolder folder = await folderPicker.PickSingleFolderAsync();

            return(folder);
        }
Exemple #23
0
        /// <summary>
        /// Load strokes from .ink file to InkCanvas
        /// </summary>
        /// <param name="inkCanvas">InkCanvas Object</param>
        /// <param name="location">PickerLocationId</param>
        /// <returns>Task</returns>
        public static async Task LoadInkFile(InkCanvas inkCanvas, PickerLocationId location)
        {
            var picker = new FileOpenPicker
            {
                SuggestedStartLocation = location
            };

            picker.FileTypeFilter.Add(".ink");
            var pickedFile = await picker.PickSingleFileAsync();

            if (pickedFile != null)
            {
                var file = await pickedFile.OpenReadAsync();

                await inkCanvas.InkPresenter.StrokeContainer.LoadAsync(file);
            }
        }
Exemple #24
0
        public static async Task <IReadOnlyList <StorageFile> > OpenFileMulti(PickerLocationId locationId, string[] fileExtensions)
        {
            FileOpenPicker openPicker = new FileOpenPicker()
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = locationId
            };

            foreach (var ext in fileExtensions)
            {
                openPicker.FileTypeFilter.Add(ext);
            }

            var files = await openPicker.PickMultipleFilesAsync();

            return(files);
        }
		/// <summary>
		/// Opens a file picker and allows the user to pick multiple files and return a list of the files the user chose
		/// </summary>
		/// <param name="location"></param>
		/// <param name="filterTypes"></param>
		/// <returns></returns>
		public async Task<IReadOnlyList<StorageFile>> PickMultipleFilesAsync(
			PickerLocationId location = PickerLocationId.DocumentsLibrary, params string[] filterTypes)
		{
			FileOpenPicker openPicker = new FileOpenPicker();

			openPicker.SuggestedStartLocation = location;

			if (filterTypes != null)
			{
				foreach (string filterType in filterTypes)
				{
					openPicker.FileTypeFilter.Add(filterType);
				}
			}

			return await openPicker.PickMultipleFilesAsync();
		}
Exemple #26
0
        /// <summary>
        /// Save InkCanvas strokes to .ink File
        /// </summary>
        /// <param name="inkCanvas">InkCanvas Object</param>
        /// <param name="location">PickerLocationId</param>
        /// <returns>Success or not</returns>
        public static async Task <Response> SaveToInkFile(InkCanvas inkCanvas, PickerLocationId location)
        {
            IRandomAccessStream stream = new InMemoryRandomAccessStream();

            var strokes = inkCanvas.InkPresenter.StrokeContainer.GetStrokes();

            if (strokes.Any())
            {
                await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream);

                var picker = new FileSavePicker
                {
                    SuggestedStartLocation = location
                };
                picker.FileTypeChoices.Add("INK files", new List <string> {
                    ".ink"
                });
                var file = await picker.PickSaveFileAsync();

                if (file == null)
                {
                    return(new Response
                    {
                        IsSuccess = false,
                        Message = $"{nameof(file)} is null"
                    });
                }

                CachedFileManager.DeferUpdates(file);
                var bt = await Utils.ConvertImagetoByte(stream);

                await FileIO.WriteBytesAsync(file, bt);

                await CachedFileManager.CompleteUpdatesAsync(file);

                return(new Response
                {
                    IsSuccess = true
                });
            }
            return(new Response
            {
                IsSuccess = false
            });
        }
		/// <summary>
		/// Opens a file picker and allows the user to pick one file and returns a StorageFile to the caller
		/// </summary>
		/// <param name="location"></param>
		/// <param name="filterTypes"></param>
		/// <returns></returns>
		public async Task<StorageFile> PickFileAsync(PickerLocationId location = PickerLocationId.DocumentsLibrary,
																				 params string[] filterTypes)
		{
			FileOpenPicker openPicker = new FileOpenPicker
			                            {
				                            SuggestedStartLocation = location
			                            };

			if (filterTypes != null)
			{
				foreach (string filterType in filterTypes)
				{
					openPicker.FileTypeFilter.Add(filterType);
				}
			}

			return await openPicker.PickSingleFileAsync();
		}
        public async static Task <StorageFolder> PickFolder(PickerLocationId pickerLocationId = PickerLocationId.Desktop)
        {
            var folderPicker = new FolderPicker();

            folderPicker.SuggestedStartLocation = pickerLocationId;
            folderPicker.FileTypeFilter.Add("*");

            StorageFolder folder = await folderPicker.PickSingleFolderAsync();

            if (folder != null)
            {
                // Application now has read/write access to all contents in the picked folder
                // (including other sub-folder contents)
                return(folder);
            }

            Console.WriteLine("Operation Cancelled");
            return(null);
        }
Exemple #29
0
        private static PickerLocationId getFolderType(FolderLocations folderLocation)
        {
            PickerLocationId folder = PickerLocationId.Desktop;

            switch (folderLocation)
            {
            case FolderLocations.Documents: folder = PickerLocationId.DocumentsLibrary; break;

            case FolderLocations.Pictures: folder = PickerLocationId.PicturesLibrary; break;

            case FolderLocations.Music: folder = PickerLocationId.MusicLibrary; break;

            case FolderLocations.Video: folder = PickerLocationId.VideosLibrary; break;

            default: Debug.ThrowError("Streams", "Unsuported folder location"); break;
            }

            return(folder);
        }
        public async static Task <StorageFile> PickSingleImageFileAsync(PickerLocationId location)
        {
            // Picker
            FileOpenPicker openPicker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = location,
                FileTypeFilter         =
                {
                    ".jpg",
                    ".jpeg",
                    ".png",
                    ".bmp"
                }
            };

            // File
            StorageFile file = await openPicker.PickSingleFileAsync();

            return(file);
        }
Exemple #31
0
        /// <summary>
        /// Save InkCanvas strokes to .ink File
        /// </summary>
        /// <param name="inkCanvas">InkCanvas Object</param>
        /// <param name="location">PickerLocationId</param>
        /// <returns>Success or not</returns>
        public static async Task<Response> SaveToInkFile(InkCanvas inkCanvas, PickerLocationId location)
        {
            IRandomAccessStream stream = new InMemoryRandomAccessStream();

            var strokes = inkCanvas.InkPresenter.StrokeContainer.GetStrokes();
            if (strokes.Any())
            {
                await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream);

                var picker = new FileSavePicker
                {

                    SuggestedStartLocation = location
                };
                picker.FileTypeChoices.Add("INK files", new List<string> { ".ink" });
                var file = await picker.PickSaveFileAsync();
                if (file == null)
                {
                    return new Response
                    {
                        IsSuccess = false,
                        Message = $"{nameof(file)} is null"
                    };
                }

                CachedFileManager.DeferUpdates(file);
                var bt = await Utils.ConvertImagetoByte(stream);
                await FileIO.WriteBytesAsync(file, bt);
                await CachedFileManager.CompleteUpdatesAsync(file);

                return new Response
                {
                    IsSuccess = true
                };
            }
            return new Response
            {
                IsSuccess = false
            };
        }
Exemple #32
0
        /// <summary>
        /// Save InkCanvas strokes to .ink File
        /// </summary>
        /// <param name="inkCanvas">InkCanvas Object</param>
        /// <param name="location">PickerLocationId</param>
        /// <returns>Success or not</returns>
        public static async Task <Response> SaveToInkFile(InkCanvas inkCanvas, PickerLocationId location)
        {
            var picker = new FileSavePicker
            {
                SuggestedStartLocation = location
            };

            picker.FileTypeChoices.Add("INK files", new List <string> {
                ".ink"
            });
            var file = await picker.PickSaveFileAsync();

            if (file == null)
            {
                return(new Response
                {
                    IsSuccess = false,
                    Message = $"{nameof(file)} is null"
                });
            }
            return(await SaveToStorageFile(inkCanvas, file));
        }
        public 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))
                {
                    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,
                                         96.0,
                                         96.0,
                                         pixels);
                    await encoder.FlushAsync();
                }

                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(sFile);

                return(status);
            }
            return(FileUpdateStatus.Failed);
        }
Exemple #34
0
        public static SpecialFolder GetInitialSpecialFolder(PickerLocationId location)
        {
            switch (location)
            {
            case PickerLocationId.DocumentsLibrary:
                return(SpecialFolder.MyDocuments);

            case PickerLocationId.Desktop:
                return(SpecialFolder.Desktop);

            case PickerLocationId.MusicLibrary:
                return(SpecialFolder.MyMusic);

            case PickerLocationId.PicturesLibrary:
                return(SpecialFolder.MyPictures);

            case PickerLocationId.VideosLibrary:
                return(SpecialFolder.MyVideos);

            default:
                return(SpecialFolder.MyComputer);
            }
        }
Exemple #35
0
        public async Task <FileUpdateStatus> ExportInkToImageFile(PickerLocationId location, string fileName, Color backgroundColor)
        {
            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);
                CanvasDevice device = CanvasDevice.GetSharedDevice();

                var localDpi = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().LogicalDpi;
                CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (int)InkCanvas.ActualWidth, (int)InkCanvas.ActualHeight, localDpi);

                using (var ds = renderTarget.CreateDrawingSession())
                {
                    ds.Clear(backgroundColor);
                    ds.DrawInk(InkCanvas.InkPresenter.StrokeContainer.GetStrokes());
                }

                using (var fileStream = await sFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Png, 1f);
                }

                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(sFile);

                return(status);
            }
            return(FileUpdateStatus.Failed);
        }
        /// <summary>
        /// Displays a file open dialog to the user.
        /// </summary>
        /// <param name="commitButtonText">The text, that is displayed on the commit button, that the user has to press to select one or multiple files.</param>
        /// <param name="fileTypeFilter">The file type filter, which determines which kinds of files are displayed to the user.</param>
        /// <param name="suggestedStartLocation">The suggested start location, which is initally displayed by the open file dialog.</param>
        /// <param name="viewMode">The view mode, which determines whether the open file dialog displays the files as a list or as thumbnails.</param>
        /// <param name="isMultiselect">Determines whether the user is able to select multiple files.</param>
        /// <returns>Returns the dialog result and the files that were selected by the user.</returns>
        public virtual async Task<DialogResult<IEnumerable<StorageFile>>> ShowOpenFileDialogAsync(string commitButtonText, IEnumerable<string> fileTypeFilter, PickerLocationId suggestedStartLocation, PickerViewMode viewMode, bool isMultiselect)
        {
            // Creates a new task completion source for the result of the open file dialog
            TaskCompletionSource<IEnumerable<StorageFile>> taskCompletionSource = new TaskCompletionSource<IEnumerable<StorageFile>>();

            // Executes the open file dialog on the dispatcher thread of the current core application view, this is needed so that the code is always executed on the UI thread
            await CoreApplication.GetCurrentView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
            {
                // Creates a new open file dialog
                FileOpenPicker fileOpenPicker = new FileOpenPicker
                {
                    CommitButtonText = commitButtonText,
                    SuggestedStartLocation = suggestedStartLocation,
                    ViewMode = viewMode
                };
                foreach (string currentFileTypeFilter in fileTypeFilter)
                    fileOpenPicker.FileTypeFilter.Add(currentFileTypeFilter == "*" ? currentFileTypeFilter : $".{currentFileTypeFilter}");

                // Shows the open file dialog and stores the result
                if (isMultiselect)
                    taskCompletionSource.TrySetResult(await fileOpenPicker.PickMultipleFilesAsync());
                else
                    taskCompletionSource.TrySetResult(new List<StorageFile> { await fileOpenPicker.PickSingleFileAsync() });
            });

            // Checks if the user cancelled the open file dialog, if so then cancel is returned, otherwise okay is returned with the files that were picked by the user
            IEnumerable<StorageFile> storageFiles = await taskCompletionSource.Task;
            if (storageFiles == null || !storageFiles.Any() || storageFiles.Any(storageFile => storageFile == null))
                return new DialogResult<IEnumerable<StorageFile>>(DialogResult.Cancel, null);
            else
                return new DialogResult<IEnumerable<StorageFile>>(DialogResult.Okay, storageFiles);
        }
        private static async Task <StorageFile> PickFileAsync(string fileName, string key, IList <string> values, PickerLocationId suggestedLocation = PickerLocationId.PicturesLibrary)
        {
            var savePicker = new FileSavePicker
            {
                SuggestedStartLocation = suggestedLocation
            };

            savePicker.FileTypeChoices.Add(key, values);
            savePicker.SuggestedFileName = fileName;

            try
            {
                return(await savePicker.PickSaveFileAsync());
            }
            catch (Exception)
            {
                return(null);
            }
        }
        /// <summary>
        /// Displays a save file dialog to the user.
        /// </summary>
        /// <param name="commitButtonText">The text, that is displayed on the commit button, that the user has to press to select a file.</param>
        /// <param name="fileTypeChoices">The file type filter, which determines which kinds of files are available to the user.</param>
        /// <param name="suggestedSaveFile">The file which is suggested to the user as the file to which he is saving.</param>
        /// <param name="suggestedStartLocation">The suggested start location, which is initally displayed by the save file dialog.</param>
        /// <returns>Returns the dialog result with the file that was selected by the user.</returns>
        public virtual async Task<DialogResult<StorageFile>> ShowSaveFileDialogAsync(string commitButtonText, IEnumerable<FileTypeRestriction> fileTypeChoices, StorageFile suggestedSaveFile, PickerLocationId suggestedStartLocation)
        {
            // Creates a new task completion source for the result of the save file dialog
            TaskCompletionSource<StorageFile> taskCompletionSource = new TaskCompletionSource<StorageFile>();

            // Executes the save file dialog on the dispatcher thread of the current core application view, this is needed so that the code is always executed on the UI thread
            await CoreApplication.GetCurrentView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
            {
                // Creates a new save file dialog
                FileSavePicker fileSavePicker = new FileSavePicker
                {
                    CommitButtonText = commitButtonText,
                    SuggestedStartLocation = suggestedStartLocation
                };
                if (suggestedSaveFile != null)
                    fileSavePicker.SuggestedSaveFile = suggestedSaveFile;
                foreach (FileTypeRestriction fileTypeRestriction in fileTypeChoices)
                    fileSavePicker.FileTypeChoices.Add(fileTypeRestriction.FileTypesDescription, fileTypeRestriction.FileTypes.Select(fileType => fileType == "*" ? fileType : $".{fileType}").ToList());

                // Shows the save file dialog and stores the result
                taskCompletionSource.TrySetResult(await fileSavePicker.PickSaveFileAsync());
            });

            // Checks if the user cancelled the save file dialog, if so then cancel is returned, otherwise okay is returned with the file that was picked by the user
            StorageFile storageFile = await taskCompletionSource.Task;
            if (storageFile == null)
                return new DialogResult<StorageFile>(DialogResult.Cancel, null);
            else
                return new DialogResult<StorageFile>(DialogResult.Okay, storageFile);
        }
        public async static Task <IReadOnlyList <StorageFile> > PickMultipleImageFilesAsync(PickerLocationId location)
        {
            // Picker
            FileOpenPicker openPicker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = location,
                FileTypeFilter         =
                {
                    ".jpg",
                    ".jpeg",
                    ".png",
                    ".bmp"
                }
            };

            // File
            IReadOnlyList <StorageFile> files = await openPicker.PickMultipleFilesAsync();

            return(files);
        }
        /// <summary>
        /// Displays a folder browser dialog to the user.
        /// </summary>
        /// <param name="commitButtonText">The text, that is displayed on the commit button, that the user has to press to select a folder.</param>
        /// <param name="suggestedStartLocation">The suggested start location, which is initally displayed by the browse folder dialog.</param>
        /// <param name="viewMode">The view mode, which determines whether the browse folder dialog displays the folders as a list or as thumbnails.</param>
        /// <returns>Returns the dialog result and the folder that was selected by the user.</returns>
        public virtual async Task<DialogResult<StorageFolder>> ShowFolderBrowseDialogAsync(string commitButtonText, PickerLocationId suggestedStartLocation, PickerViewMode viewMode)
        {
            // Creates a new task completion source for the result of the folder browser dialog
            TaskCompletionSource<StorageFolder> taskCompletionSource = new TaskCompletionSource<StorageFolder>();

            // Executes the folder browser dialog on the dispatcher thread of the current core application view, this is needed so that the code is always executed on the UI thread
            await CoreApplication.GetCurrentView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
            {
                // Creates a new browse folder dialog
                FolderPicker folderPicker = new FolderPicker
                {
                    CommitButtonText = commitButtonText,
                    SuggestedStartLocation = suggestedStartLocation,
                    ViewMode = viewMode
                };

                // Shows the browse folder dialog and stores the result
                taskCompletionSource.TrySetResult(await folderPicker.PickSingleFolderAsync());
            });

            // Checks if the user cancelled the browse folder dialog, if so then cancel is returned, otherwise okay is returned with the folder that was picked by the user
            StorageFolder storageFolder = await taskCompletionSource.Task;
            if (storageFolder == null)
                return new DialogResult<StorageFolder>(DialogResult.Cancel, null);
            else
                return new DialogResult<StorageFolder>(DialogResult.Okay, storageFolder);
        }
		public async Task<string> PickFileAsync(PickerLocationId location, params string[] filterTypes)
		{
			OpenFileDialog openFileDialog = new OpenFileDialog();

			openFileDialog.InitialDirectory = TranslateLocation(location);

			openFileDialog.Multiselect = false;
			openFileDialog.ShowDialog();

			return openFileDialog.FileName;
		}
		public async Task<string> PickSaveFileAsync(PickerLocationId location, params string[] filterTypes)
		{
			SaveFileDialog saveFileDialog = new SaveFileDialog();

			saveFileDialog.InitialDirectory = TranslateLocation(location);

			saveFileDialog.ShowDialog();

			return saveFileDialog.FileName;
		}
		private string TranslateLocation(PickerLocationId location)
		{
			return translator.Translate(location);
		}
		/// <summary>
		/// Opens a file picker and allows the user to pick multiple files and return a list of the files the user chose
		/// </summary>
		/// <param name="location"></param>
		/// <param name="filterTypes"></param>
		/// <returns></returns>
		public async Task<IReadOnlyList<string>> PickMultipleFilesAsync(PickerLocationId location, params string[] filterTypes)
		{
			OpenFileDialog openFileDialog = new OpenFileDialog();

			openFileDialog.InitialDirectory = TranslateLocation(location);

			openFileDialog.Multiselect = true;
			openFileDialog.ShowDialog();

			if (openFileDialog.FileNames != null)
			{
				return new List<string>(openFileDialog.FileNames);
			}

			return new List<string>();
		}
        /// <summary>
        /// Displays a file open dialog to the user.
        /// </summary>
        /// <param name="commitButtonText">The text, that is displayed on the commit button, that the user has to press to select a file.</param>
        /// <param name="fileTypeFilter">The file type filter, which determines which kinds of files are displayed to the user.</param>
        /// <param name="suggestedStartLocation">The suggested start location, which is initally displayed by the open file dialog.</param>
        /// <param name="viewMode">The view mode, which determines whether the open file dialog displays the files as a list or as thumbnails.</param>
        /// <returns>Returns the dialog result and the file that was selected by the user.</returns>
        public virtual async Task<DialogResult<StorageFile>> ShowOpenFileDialogAsync(string commitButtonText, IEnumerable<string> fileTypeFilter, PickerLocationId suggestedStartLocation, PickerViewMode viewMode)
        {
            // Shows the open file dialog to the user
            DialogResult<IEnumerable<StorageFile>> dialogResult = await this.ShowOpenFileDialogAsync(commitButtonText, fileTypeFilter, suggestedStartLocation, viewMode, false);

            // Checks if the user picked a file, in that case the first one is returned
            if (dialogResult.Result == DialogResult.Cancel)
                return new DialogResult<StorageFile>(DialogResult.Cancel, null);
            else
                return new DialogResult<StorageFile>(DialogResult.Okay, dialogResult.ResultValue.FirstOrDefault());
        }
Exemple #46
0
 /// <summary>
 /// Load strokes from .ink file to InkCanvas
 /// </summary>
 /// <param name="inkCanvas">InkCanvas Object</param>
 /// <param name="location">PickerLocationId</param>
 /// <returns>Task</returns>
 public static async Task LoadInkFile(InkCanvas inkCanvas, PickerLocationId location)
 {
     var picker = new FileOpenPicker
     {
         SuggestedStartLocation = location
     };
     picker.FileTypeFilter.Add(".ink");
     var pickedFile = await picker.PickSingleFileAsync();
     if (pickedFile != null)
     {
         var file = await pickedFile.OpenReadAsync();
         await inkCanvas.InkPresenter.StrokeContainer.LoadAsync(file);
     }
 }