コード例 #1
0
        /// <summary>
        /// Implementation for picking a file on UWP platform.
        /// </summary>
        /// <param name="allowedTypes">
        /// Specifies one or multiple allowed types. When null, all file types
        /// can be selected while picking.
        /// On UWP, specify a list of extensions, like this: ".jpg", ".png".
        /// </param>
        /// <returns>
        /// File data object, or null when user cancelled picking file
        /// </returns>
        private static async Task <FileResult> PickFileAsync(string[] allowedTypes = null)
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker
            {
                ViewMode = Windows.Storage.Pickers.PickerViewMode.List,
                SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary
            };

            var hwnd = Window.Current.CoreWindow.As <IWindowNative>().WindowHandle;
            var initializeWithWindow = picker.As <IInitializeWithWindow>();

            initializeWithWindow.Initialize(hwnd);

            if (allowedTypes is not null)
            {
                var hasAtleastOneType = false;

                foreach (var type in allowedTypes.Where(q => q.StartsWith(".")))
                {
                    picker.FileTypeFilter.Add(type);
                    hasAtleastOneType = true;
                }

                if (!hasAtleastOneType)
                {
                    picker.FileTypeFilter.Add("*");
                }
            }
            else
            {
                picker.FileTypeFilter.Add("*");
            }

            if (await picker.PickSingleFileAsync() is StorageFile file)
            {
                StorageApplicationPermissions.FutureAccessList.Add(file);

                return(new FileResult(
                           file.Path,
                           file.Name,
                           () => file.OpenStreamForReadAsync().GetAwaiter().GetResult()));
            }

            return(null);
        }