Example #1
0
        async Task <IEnumerable <FileResult> > PlatformPickAsync(PickOptions options, bool allowMultiple = false)
        {
            var allowedUtis = options?.FileTypes?.Value?.ToArray() ?? new string[]
            {
                UTType.Content,
                UTType.Item,
                "public.data"
            };

            var tcs = new TaskCompletionSource <IEnumerable <FileResult> >();

            // Use Open instead of Import so that we can attempt to use the original file.
            // If the file is from an external provider, then it will be downloaded.
            using var documentPicker = new UIDocumentPickerViewController(allowedUtis, UIDocumentPickerMode.Open);
            if (OperatingSystem.IsIOSVersionAtLeast(11, 0))
            {
                documentPicker.AllowsMultipleSelection = allowMultiple;
            }
            documentPicker.Delegate = new PickerDelegate
            {
                PickHandler = urls => GetFileResults(urls, tcs)
            };

            if (documentPicker.PresentationController != null)
            {
                documentPicker.PresentationController.Delegate =
                    new UIPresentationControllerDelegate(() => GetFileResults(null, tcs));
            }

            var parentController = WindowStateManager.Default.GetCurrentUIViewController(true);

            parentController.PresentViewController(documentPicker, true, null);

            return(await tcs.Task);
        }
Example #2
0
        private async void ButtonImportDb_Click(object sender, EventArgs e)
        {
            PickOptions options = new PickOptions();

            options.PickerTitle = "Datenbank oder Backup auswählen:";

            var file = await FilePicker.PickAsync(options);

            if (file == null)
            {
                return;
            }

            Exception ex = Android_Database.Instance.ImportDatabase(this, file.FullPath, file.FileName);

            if (ex != null)
            {
                var message = new AlertDialog.Builder(this);
                message.SetMessage(ex.Message);
                message.SetPositiveButton("OK", (s, e) => { });
                message.Create().Show();
            }

            return;
        }
        private async Task CustomFileTypes(params string[] args)
        {
            try
            {
                var customFileType =
                    new FilePickerFileType(new Dictionary <DevicePlatform, IEnumerable <string> >
                {
                    { DevicePlatform.iOS, args }, // or general UTType values
                    { DevicePlatform.Android, args },
                    { DevicePlatform.UWP, args }
                });

                var options = new PickOptions
                {
                    PickerTitle = "Please select a file file",
                    FileTypes   = customFileType,
                };

                var result = await FilePicker.PickAsync(options);

                if (result != null)
                {
                    lFileName.Text = result.FileName;
                    lFilePath.Text = result.FullPath;
                }
            }
            catch (Exception ex)
            {
                lFileName.Text = ex.ToString();
                lFilePath.Text = string.Empty;
            }
        }
Example #4
0
        private async Task ReadFileAsync()
        {
            // pick file
            var options = new PickOptions
            {
                PickerTitle = "Title"
            };
            var result = await FilePicker.PickAsync(options);

            if (result == null)
            {
                Trace.WriteLine("PickAsync result is null");
                return;
            }

            Trace.WriteLine($"File path: {result.FullPath}");

            // open file and read content
            using (var reader = new StreamReader(await result.OpenReadAsync()))
            {
                var content = await reader.ReadToEndAsync();

                Trace.WriteLine($"File content: {content}");
            }
        }
Example #5
0
        /// <summary>
        /// Open a .sketch360 file
        /// </summary>
        /// <param name="parameter">the parameter is not used.</param>
        /// <returns>an async task</returns>
        protected override async Task ExecuteAsync(object parameter)
        {
            var customFileType =
                new FilePickerFileType(new Dictionary <DevicePlatform, IEnumerable <string> >
            {
                { DevicePlatform.Android, new[] { "application/octet-stream" } },
                { DevicePlatform.UWP, new[] { "application/octet-stream" } },
            });

            var options = new PickOptions
            {
                PickerTitle = "Please select a Sketch 360 File",
                FileTypes   = customFileType,
            };

            var fileData = await Xamarin.Essentials.FilePicker.PickAsync(options).ConfigureAwait(true);

            if (fileData == null)
            {
                return;
            }
            using var stream = await fileData.OpenReadStreamAsync().ConfigureAwait(true);

            using var zipFile = new ZipFile(stream);
            var entry = zipFile.GetEntry("sketch360.json");

            using var jsonStream = zipFile.GetInputStream(entry);
            using var reader     = new StreamReader(jsonStream);
            var json = await reader.ReadToEndAsync().ConfigureAwait(true);

            (App.Current as App).LoadSketch(json);
        }
Example #6
0
        static async Task <IEnumerable <FilePickerResult> > PlatformPickAsync(PickOptions options, bool allowMultiple = false)
        {
            // we only need the permission when accessing the file, but it's more natural
            // to ask the user first, then show the picker.
            await Permissions.RequestAsync <Permissions.StorageRead>();

            // Essentials supports >= API 19 where this action is available
            var action = Intent.ActionOpenDocument;

            var intent = new Intent(action);

            intent.SetType("*/*");
            intent.AddFlags(ActivityFlags.GrantPersistableUriPermission);
            intent.PutExtra(Intent.ExtraAllowMultiple, allowMultiple);

            var allowedTypes = options?.FileTypes?.Value?.ToArray();

            if (allowedTypes?.Length > 0)
            {
                intent.PutExtra(Intent.ExtraMimeTypes, allowedTypes);
            }

            var pickerIntent = Intent.CreateChooser(intent, options?.PickerTitle ?? "Select file");

            try
            {
                var result = await IntermediateActivity.StartAsync(pickerIntent, requestCodeFilePicker);

                var resultList = new List <FilePickerResult>();

                var clipData = new List <global::Android.Net.Uri>();

                if (result.ClipData == null)
                {
                    clipData.Add(result.Data);
                }
                else
                {
                    for (var i = 0; i < result.ClipData.ItemCount; i++)
                    {
                        clipData.Add(result.ClipData.GetItemAt(i).Uri);
                    }
                }

                foreach (var contentUri in clipData)
                {
                    Platform.AppContext.ContentResolver.TakePersistableUriPermission(
                        contentUri,
                        ActivityFlags.GrantReadUriPermission);

                    resultList.Add(new FilePickerResult(contentUri));
                }

                return(resultList);
            }
            catch (OperationCanceledException)
            {
                return(null);
            }
        }
Example #7
0
        private async void chooseImage(object sender, RoutedEventArgs e)
        {
            var customFileType =
                new FilePickerFileType(new Dictionary <DevicePlatform, IEnumerable <string> >
            {
                { DevicePlatform.Android, new string[] { "image/png", "image/jpeg" } },
                { DevicePlatform.UWP, new string[] { ".jpg", ".png" } }
            });
            var options = new PickOptions
            {
                PickerTitle = "Pilih Gambar..",
                FileTypes   = customFileType,
            };
            var result = await FilePicker.PickAsync(options);

            byte[] hasil;
            if (result != null)
            {
                Stream stream = await result.OpenReadAsync();

                using (var streamReader = new MemoryStream())
                {
                    stream.CopyTo(streamReader);
                    hasil = streamReader.ToArray();
                }
                string fileName = result.FileName;
                imageLaporan             = new UploadedImage(fileName, hasil, 0);
                txtNamaFile.Text         = fileName;
                gridFile.Visibility      = Visibility.Visible;
                txtStatusFile.Visibility = Visibility.Collapsed;
            }
        }
Example #8
0
        async Task PickAndShow(PickOptions options = null)
        {
            try
            {
                var result = await FilePicker.PickAsync();

                if (result != null)
                {
                    Console.WriteLine($"File Name: {result.FileName}");
                    var stream = await result.OpenReadAsync();

                    var buf1     = new byte[16];
                    var readCnt  = stream.Read(buf1, 0, 16);
                    var buf2     = new byte[16];
                    var readCnt2 = stream.Read(buf2, 0, 16);
                    Console.WriteLine(readCnt2);

                    /*if (result.FileName.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) ||
                     *  result.FileName.EndsWith("png", StringComparison.OrdinalIgnoreCase))
                     * {
                     *  // var stream = await result.OpenReadAsync();
                     *  // Image = ImageSource.FromStream(() => stream);
                     * }*/
                }
            }
            catch (Exception ex)
            {
                // The user canceled or something went wrong
            }
        }
Example #9
0
        //Set the feed icon
        private async void btn_SetIcon_Clicked(object sender, EventArgs e)
        {
            try
            {
                Feeds SelectedItem = (Feeds)listview_Items.SelectedItem;
                if (SelectedItem != null)
                {
                    List <string> messageAnswers = new List <string>();
                    messageAnswers.Add("Set custom icon");
                    messageAnswers.Add("Reset the icon");
                    messageAnswers.Add("Cancel");

                    string messageResult = await MessagePopup.Popup("Change the feed icon", "Would you like to set a custom feed icon for " + SelectedItem.feed_title + "?", messageAnswers);

                    if (messageResult == "Set custom icon")
                    {
                        Debug.WriteLine("Changing icon for feed: " + SelectedItem.feed_id + " / " + SelectedItem.feed_title);

                        PickOptions pickOptions = new PickOptions();
                        pickOptions.FileTypes = FilePickerFileType.Png;

                        FileResult pickResult = await FilePicker.PickAsync(pickOptions);

                        if (pickResult != null)
                        {
                            //Load feed icon
                            Stream imageStream = await pickResult.OpenReadAsync();

                            //Update feed icon
                            if (imageStream.CanSeek)
                            {
                                imageStream.Position = 0;
                            }
                            SelectedItem.feed_icon = ImageSource.FromStream(() => imageStream);

                            //Save feed icon
                            AVFiles.File_SaveStream(SelectedItem.feed_id + ".png", imageStream, true, true);
                        }
                    }
                    else if (messageResult == "Reset the icon")
                    {
                        //Delete the feed icon
                        AVFiles.File_Delete(SelectedItem.feed_id + ".png", true);

                        //Load default feed icon
                        SelectedItem.feed_icon = ImageSource.FromResource("NewsScroll.Assets.iconRSS-Dark.png");

                        //Reset the online status
                        OnlineUpdateFeeds = true;
                        ApiMessageError   = string.Empty;

                        List <string> messageAnswersReset = new List <string>();
                        messageAnswersReset.Add("Ok");

                        await MessagePopup.Popup("Feed icon reset", "The feed icon has been reset and will be refreshed on the next online feed update, you can refresh the feeds by clicking on the refresh icon above.", messageAnswersReset);
                    }
                }
            }
            catch { }
        }
Example #10
0
        static async Task <IEnumerable <FilePickerResult> > PlatformPickAsync(PickOptions options, bool allowMultiple = false)
        {
            Permissions.EnsureDeclared <Permissions.LaunchApp>();
            await Permissions.EnsureGrantedAsync <Permissions.StorageRead>();

            var tcs = new TaskCompletionSource <IEnumerable <FilePickerResult> >();

            var appControl = new AppControl();

            appControl.Operation = AppControlOperations.Pick;
            appControl.ExtraData.Add(AppControlData.SectionMode, allowMultiple ? "multiple" : "single");
            appControl.LaunchMode = AppControlLaunchMode.Single;

            var fileType = options?.FileTypes?.Value?.FirstOrDefault();

            appControl.Mime = fileType ?? "*/*";

            var fileResults = new List <FilePickerResult>();

            AppControl.SendLaunchRequest(appControl, (request, reply, result) =>
            {
                if (result == AppControlReplyResult.Succeeded)
                {
                    if (reply.ExtraData.Count() > 0)
                    {
                        var selectedFiles = reply.ExtraData.Get <IEnumerable <string> >(AppControlData.Selected).ToList();
                        fileResults.AddRange(selectedFiles.Select(f => new FilePickerResult(f)));
                    }
                }

                tcs.TrySetResult(fileResults);
            });

            return(await tcs.Task);
        }
Example #11
0
        static Task <IEnumerable <FileResult> > PlatformPickAsync(PickOptions options, bool allowMultiple = false)
        {
            var openPanel = new NSOpenPanel
            {
                CanChooseFiles          = true,
                AllowsMultipleSelection = allowMultiple,
                CanChooseDirectories    = false
            };

            if (options.PickerTitle != null)
            {
                openPanel.Title = options.PickerTitle;
            }

            SetFileTypes(options, openPanel);

            var resultList  = new List <FileResult>();
            var panelResult = openPanel.RunModal();

            if (panelResult == (nint)(long)NSModalResponse.OK)
            {
                foreach (var url in openPanel.Urls)
                {
                    resultList.Add(new FileResult(url.Path));
                }
            }

            return(Task.FromResult <IEnumerable <FileResult> >(resultList));
        }
        static async Task <IEnumerable <FileResult> > PlatformPickAsync(PickOptions options, bool allowMultiple = false)
        {
            // we only need the permission when accessing the file, but it's more natural
            // to ask the user first, then show the picker.
            await Permissions.RequestAsync <Permissions.StorageRead>();

            // Essentials supports >= API 19 where this action is available
            var action = Intent.ActionOpenDocument;

            var intent = new Intent(action);

            intent.SetType(FileSystem.MimeTypes.All);
            intent.PutExtra(Intent.ExtraAllowMultiple, allowMultiple);

            var allowedTypes = options?.FileTypes?.Value?.ToArray();

            if (allowedTypes?.Length > 0)
            {
                intent.PutExtra(Intent.ExtraMimeTypes, allowedTypes);
            }

            var pickerIntent = Intent.CreateChooser(intent, options?.PickerTitle ?? "Select file");

            try
            {
                var resultList = new List <FileResult>();
                void OnResult(Intent intent)
                {
                    // The uri returned is only temporary and only lives as long as the Activity that requested it,
                    // so this means that it will always be cleaned up by the time we need it because we are using
                    // an intermediate activity.

                    if (intent.ClipData == null)
                    {
                        var path = FileSystem.EnsurePhysicalPath(intent.Data);
                        resultList.Add(new FileResult(path));
                    }
                    else
                    {
                        for (var i = 0; i < intent.ClipData.ItemCount; i++)
                        {
                            var uri  = intent.ClipData.GetItemAt(i).Uri;
                            var path = FileSystem.EnsurePhysicalPath(uri);
                            resultList.Add(new FileResult(path));
                        }
                    }
                }

                await IntermediateActivity.StartAsync(pickerIntent, Platform.requestCodeFilePicker, onResult : OnResult);

                return(resultList);
            }
            catch (OperationCanceledException)
            {
                return(null);
            }
        }
Example #13
0
        private void FabOnClick(object sender, EventArgs eventArgs)
        {
            View view = (View)sender;


            var options = new PickOptions
            {
                PickerTitle = "Please select a PKG file",
                //FileTypes = customFileType,
            };
            var item = PickAndShow(options, view);
        }
Example #14
0
        static Task <IEnumerable <FileResult> > PlatformPickAsync(PickOptions options, bool allowMultiple = false)
        {
            if (allowMultiple && !Platform.HasOSVersion(11, 0))
            {
                throw new FeatureNotSupportedException("Multiple file picking is only available on iOS 11 or later.");
            }

            var allowedUtis = options?.FileTypes?.Value?.ToArray() ?? new string[]
            {
                UTType.Content,
                UTType.Item,
                "public.data"
            };

            var tcs = new TaskCompletionSource <IEnumerable <FileResult> >();

            // Note: Importing (UIDocumentPickerMode.Import) makes a local copy of the document,
            // while opening (UIDocumentPickerMode.Open) opens the document directly. We do the
            // latter, so the user accesses the original file.
            var documentPicker = new UIDocumentPickerViewController(allowedUtis, UIDocumentPickerMode.Open);

            documentPicker.AllowsMultipleSelection = allowMultiple;
            documentPicker.Delegate = new PickerDelegate
            {
                PickHandler = urls =>
                {
                    try
                    {
                        // there was a cancellation
                        if (urls?.Any() ?? false)
                        {
                            tcs.TrySetResult(urls.Select(url => new UIDocumentFileResult(url)));
                        }
                        else
                        {
                            tcs.TrySetResult(Enumerable.Empty <FileResult>());
                        }
                    }
                    catch (Exception ex)
                    {
                        // pass exception to task so that it doesn't get lost in the UI main loop
                        tcs.SetException(ex);
                    }
                }
            };

            var parentController = Platform.GetCurrentViewController();

            parentController.PresentViewController(documentPicker, true, null);

            return(tcs.Task);
        }
Example #15
0
        static void SetFileTypes(PickOptions options, NativeMethods.IFileOpenDialog dialog)
        {
            var hasAtLeastOneType = false;
            var filters           = new List <NativeMethods.COMDLG_FILTERSPEC>();

            if (options?.FileTypes == FilePickerFileType.Images)
            {
                var types = new StringBuilder();
                foreach (var type in options.FileTypes.Value)
                {
                    types.Append(type + ";");
                }

                filters.Add(new NativeMethods.COMDLG_FILTERSPEC {
                    pszName = "Images\0", pszSpec = types.ToString() + "\0"
                });
                hasAtLeastOneType = true;
            }
            else if (options?.FileTypes == FilePickerFileType.Videos)
            {
                var types = new StringBuilder();
                foreach (var type in options.FileTypes.Value)
                {
                    types.Append(type + ";");
                }

                filters.Add(new NativeMethods.COMDLG_FILTERSPEC {
                    pszName = "Videos\0", pszSpec = types.ToString() + "\0"
                });
                hasAtLeastOneType = true;
            }
            else if (options?.FileTypes?.Value != null)
            {
                foreach (var type in options.FileTypes.Value)
                {
                    if (type.StartsWith(".") || type.StartsWith("*."))
                    {
                        filters.Add(new NativeMethods.COMDLG_FILTERSPEC {
                            pszName = type.TrimStart('*') + "\0", pszSpec = type + "\0"
                        });
                        hasAtLeastOneType = true;
                    }
                }
            }

            if (hasAtLeastOneType)
            {
                dialog.SetFileTypes(filters.Count, filters.ToArray());
            }
        }
Example #16
0
        static void SetFileTypes(PickOptions options, NSOpenPanel panel)
        {
            var allowedFileTypes = new List <string>();

            if (options?.FileTypes?.Value != null)
            {
                foreach (var type in options.FileTypes.Value)
                {
                    allowedFileTypes.Add(type.TrimStart('*', '.'));
                }
            }

            panel.AllowedFileTypes = allowedFileTypes.ToArray();
        }
Example #17
0
        private async Task PickImage(EventArgs arg)
        {
            var options = new PickOptions {
                FileTypes = FilePickerFileType.Images
            };
            var result = await FilePicker.PickAsync(options);

            if (result != null)
            {
                var cropResult = await CropImageService.Instance.CropImage(result.FullPath, CropRatioType.None);

                if (cropResult.IsSuccess)
                {
                    Image = File.ReadAllBytes(cropResult.FilePath);
                }
            }
        }
Example #18
0
        /// <summary>
        /// Open a .sketch360 file
        /// </summary>
        /// <param name="parameter">the parameter is not used.</param>
        /// <returns>an async task</returns>
        protected override async Task ExecuteAsync(object parameter)
        {
            /// Once we stop getting opens with octet-stream, we will remove the file type and only open x-sketch360
            var customFileType =
                new FilePickerFileType(new Dictionary <DevicePlatform, IEnumerable <string> >
            {
                //{ DevicePlatform.Android, new[] { "application/x-sketch360" } },
                { DevicePlatform.Android, new[] { "application/octet-stream", "application/x-sketch360" } },
                { DevicePlatform.UWP, new[] { ".sketch360" } },
            });

            var options = new PickOptions
            {
                PickerTitle = "Please select a Sketch 360 File",
                FileTypes   = customFileType,
            };

            var fileData = await Xamarin.Essentials.FilePicker.PickAsync(options).ConfigureAwait(true);

            if (fileData == null)
            {
                return;
            }

            if (System.IO.Path.GetExtension(fileData.FileName) == ".sketch360")
            {
                using var stream = await fileData.OpenReadAsync().ConfigureAwait(true);

                using var zipFile = new ZipFile(stream);
                var entry = zipFile.GetEntry("sketch360.json");

                using var jsonStream = zipFile.GetInputStream(entry);
                using var reader     = new StreamReader(jsonStream);
                var json = await reader.ReadToEndAsync().ConfigureAwait(true);

                (App.Current as App).LoadSketch(json);
            }

            var properties = new Dictionary <string, string>
            {
                ["filename"]    = fileData.FileName,
                ["contentType"] = fileData.ContentType
            };

            Analytics.TrackEvent("Sketch Opened", properties);
        }
Example #19
0
        public static void LoadMap()
        {
            var strRoute = string.Empty;

            MainThread.BeginInvokeOnMainThread(async() =>
            {
                try
                {
                    var options = new PickOptions
                    {
                        PickerTitle = "Please select a map file",
                        FileTypes   = new FilePickerFileType(new Dictionary <DevicePlatform, IEnumerable <string> >
                        {
                            /**///What is mime type for mbtiles ?!?
                            //{ DevicePlatform.Android, new string[] { "mbtiles"} },
                            { DevicePlatform.Android, null },
                        })
                    };

                    var sourceFile = await FilePicker.PickAsync(options);
                    if (sourceFile != null)
                    {
                        string destinationFile = MainActivity.rootPath + "/MBTiles/" + sourceFile.FileName;

                        if (File.Exists(destinationFile))
                        {
                            Show_Dialog msg1 = new Show_Dialog(MainActivity.mContext);
                            if (await msg1.ShowDialog($"Overwrite", $"Overwrite '{sourceFile.FileName}'", Android.Resource.Attribute.DialogIcon, true, Show_Dialog.MessageResult.NO, Show_Dialog.MessageResult.YES) == Show_Dialog.MessageResult.NO)
                            {
                                return;
                            }
                        }

                        File.Copy(sourceFile.FullPath, destinationFile, true);
                        Fragments.Fragment_map.map.Layers.Add(CreateMbTilesLayer(destinationFile, sourceFile.FileName));

                        Show_Dialog msg2 = new Show_Dialog(MainActivity.mContext);
                        await msg2.ShowDialog($"Done", $"Map Imported and Loaded", Android.Resource.Attribute.DialogIcon, true, Show_Dialog.MessageResult.NONE, Show_Dialog.MessageResult.OK);
                    }
                }
                catch (Exception ex)
                {
                    Log.Information($"Failed to import map file: '{ex}'");
                }
            });
        }
Example #20
0
        /// <summary>
        /// Gets the CurrentDataFolder folder
        /// </summary>
        /// <returns>
        /// True if a file was picked. False if not.
        /// </returns>
        public static async Task <bool> PickCurrentInputFile()
        {
            try
            {
                FilePickerFileType customFileType =
                    new FilePickerFileType(
                        new Dictionary <DevicePlatform,
                                        IEnumerable <string> >
                {
                    //{ DevicePlatform.iOS, new[] { "public.my.comic.extension" } }, // TODO add these or general UTType values
                    { DevicePlatform.Android, new[] { "application/octet-stream" } },
                    { DevicePlatform.UWP, new[] { ".gpkg", ".gramps" } },
                    //{ DevicePlatform.macOS, new[] { "cbr" } }, // TODO add these or general UTType values
                }
                        );

                var options = new PickOptions
                {
                    PickerTitle = "Please select a Gramps input file",
                    FileTypes   = customFileType,
                };

                FileResult result = await FilePicker.PickAsync(options);

                if (result == null)
                {
                    return(false); // user canceled file picking
                }

                Debug.WriteLine("Picked file name is: " + result.FileName);

                DataStore.Instance.AD.CurrentInputStream = await result.OpenReadAsync();

                DataStore.Instance.AD.CurrentInputStreamPath = result.FullPath;
            }

            // TODO fix this. Fail and force reload next time.
            catch (Exception ex)
            {
                App.Current.Services.GetService <IErrorNotifications>().NotifyException("Exception in PickCurrentInputFile", ex);

                throw;
            }

            return(true);
        }
        private async Task RestoreBackup()
        {
            try
            {
                var options = new PickOptions
                {
                    PickerTitle = "Please select a json file",
                };

                var result = await FilePicker.PickAsync(options);

                if (result != null)
                {
                    Stream stream = await result.OpenReadAsync();

                    StreamReader streamReader = new StreamReader(stream);
                    string       json         = streamReader.ReadToEnd();
                    var          db           = JsonConvert.DeserializeObject <DatabaseModel>(json);

                    foreach (var item in db.Playlists)
                    {
                        playlistRepository.AddPlaylist(item);
                    }
                    foreach (var item in db.Positions)
                    {
                        positionRepository.AddPosition(item);
                    }
                    foreach (var item in db.SongPlaylists)
                    {
                        songPlaylistRepository.AddSongPlaylistRelation(item);
                    }
                    foreach (var item in db.SongPositions)
                    {
                        songPositionRepository.AddSongPositionRelation(item);
                    }
                    foreach (var item in db.Songs)
                    {
                        songRepository.AddSong(item);
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
Example #22
0
        static async Task <IEnumerable <FileResult> > PlatformPickAsync(PickOptions options, bool allowMultiple = false)
        {
            var picker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.List,
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };

            var hwnd = Platform.CurrentWindowHandle;

            WinRT.Interop.InitializeWithWindow.Initialize(picker, hwnd);

            SetFileTypes(options, picker);

            var resultList = new List <StorageFile>();

            if (allowMultiple)
            {
                var fileList = await picker.PickMultipleFilesAsync();

                if (fileList != null)
                {
                    resultList.AddRange(fileList);
                }
            }
            else
            {
                var file = await picker.PickSingleFileAsync();

                if (file != null)
                {
                    resultList.Add(file);
                }
            }

            foreach (var file in resultList)
            {
                StorageApplicationPermissions.FutureAccessList.Add(file);
            }

            return(resultList.Select(storageFile => new FileResult(storageFile)));
        }
Example #23
0
        // To let enduser to pick a file using specified options
        public static async Task <FileResult> PickFileAndShow(PickOptions options = null)
        {
            if (options == null)
            {
                options = GetDefaultPickOptions();
            }

            try
            {
                var result = await FilePicker.PickAsync(options);

                return(result);
            }
            catch
            {
                // The user canceled or something went wrong
            }

            return(null);
        }
Example #24
0
        static void SetFileTypes(PickOptions options, FileOpenPicker picker)
        {
            var hasAtLeastOneType = false;

            if (options?.FileTypes?.Value != null)
            {
                foreach (var type in options.FileTypes.Value)
                {
                    if (type.StartsWith(".") || type.StartsWith("*."))
                    {
                        picker.FileTypeFilter.Add(type.TrimStart('*'));
                        hasAtLeastOneType = true;
                    }
                }
            }

            if (!hasAtLeastOneType)
            {
                picker.FileTypeFilter.Add("*");
            }
        }
        private async void PickFileButtonOnClicked(object sender, System.EventArgs e)
        {
            try
            {
                var options = new PickOptions {
                    PickerTitle = "Pick a file"
                };
                var fileResult = await FilePicker.PickAsync(options);

                if (fileResult == null)
                {
                    return;
                }

                FileNameLabel.Text = fileResult.FileName;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"{GetType().Name} | {nameof(PickFileButtonOnClicked)} | {ex}");
            }
        }
Example #26
0
        static Task <IEnumerable <FileResult> > PlatformPickAsync(PickOptions options, bool allowMultiple = false)
        {
            var fod = new NativeMethods.FileOpenDialog() as NativeMethods.IFileOpenDialog;

            SetFileTypes(options, fod);
            fod.SetTitle(options.PickerTitle);
            fod.SetOptions(allowMultiple ? NativeMethods.FILEOPENDIALOGOPTIONS.FOS_ALLOWMULTISELECT : 0);

            var showResult = fod.Show(IntPtr.Zero);

            if (showResult < 0)
            {
                return(Task.FromResult <IEnumerable <FileResult> >(new List <FileResult>()));
            }

            if (allowMultiple)
            {
                fod.GetResults(out var items);
                items.GetCount(out var count);
                var results = new List <FileResult>();
                for (var i = 0; i < count; i++)
                {
                    items.GetItemAt(i, out var item);
                    item.GetDisplayName(NativeMethods.SIGDN.SIGDN_FILESYSPATH, out var path);
                    results.Add(new FileResult(path));
                }

                return(Task.FromResult <IEnumerable <FileResult> >(results));
            }
            else
            {
                fod.GetResult(out var item);
                item.GetDisplayName(NativeMethods.SIGDN.SIGDN_FILESYSPATH, out var filename);
                return(Task.FromResult <IEnumerable <FileResult> >(new List <FileResult>()
                {
                    new FileResult(filename)
                }));
            }
        }
Example #27
0
        static void SetFileTypes(PickOptions options, FileOpenPicker picker)
        {
            var hasAtLeastOneType = false;

            if (options?.FileTypes?.Value != null)
            {
                foreach (var type in options.FileTypes.Value)
                {
                    var ext = FileSystem.Extensions.Clean(type);
                    if (!string.IsNullOrWhiteSpace(ext))
                    {
                        picker.FileTypeFilter.Add(ext);
                        hasAtLeastOneType = true;
                    }
                }
            }

            if (!hasAtLeastOneType)
            {
                picker.FileTypeFilter.Add("*");
            }
        }
Example #28
0
        public static PickOptions GetDefaultPickOptions()
        {
            var customFileType = new FilePickerFileType(new Dictionary <DevicePlatform, IEnumerable <string> >
            {
                { DevicePlatform.UWP, null },       // => OK (can select any files)
                { DevicePlatform.Android, null },   // => OK (can select any files)

                { DevicePlatform.iOS, null },       // TODO - it's working ? (can specify any files ?)
                { DevicePlatform.macOS, null },     // TODO - it's working ? (can specify any files ?)

                { DevicePlatform.tvOS, null },      // it's working ? (can specify any files ?)
                { DevicePlatform.Tizen, null },     // it's working ? (can specify any files ?)
                { DevicePlatform.Unknown, null },   // it's working ? (can specify any files ?)
                { DevicePlatform.watchOS, null },   // it's working ? (can specify any files ?)
            });

            var options = new PickOptions
            {
                FileTypes = customFileType
            };

            return(options);
        }
 static Task <IEnumerable <FileResult> > PlatformPickAsync(PickOptions options, bool allowMultiple = false)
 => throw new NotImplementedInReferenceAssemblyException();
Example #30
0
        public static string strPick(string strData, string strDelimiter, PickOptions pickBegins, PickOptions pickDirection, int DelimiterInstance, bool includeFollowers)
        {
            if (!strData.Contains(strDelimiter)) return string.Empty;
            string[] tmStr = strData.Split(new string[] { strDelimiter }, StringSplitOptions.None);
            if (DelimiterInstance <= 0 || DelimiterInstance >= tmStr.Length) return string.Empty;

            string strReturn = "";
            int LIndex = 0;
            int UIndex = 0;

            if (pickBegins == PickOptions.Left && pickDirection == PickOptions.Reverse)
            {
                UIndex = DelimiterInstance - 1;
                LIndex = (int)(!(includeFollowers) ? UIndex : 0);
            }
            else if (pickBegins == PickOptions.Right && pickDirection == PickOptions.Reverse)
            {
                LIndex = (tmStr.Length - DelimiterInstance);
                UIndex = (int)(!(includeFollowers) ? LIndex : tmStr.Length - 1);
            }
            else if (pickBegins == PickOptions.Left && pickDirection == PickOptions.Forward)
            {
                LIndex = DelimiterInstance;
                UIndex = (int)(!(includeFollowers) ? LIndex : tmStr.Length - 1);
            }
            else
            {
                UIndex = (tmStr.Length - DelimiterInstance) - 1;
                LIndex = (int)(!(includeFollowers) ? UIndex : 0);
            }

            for (int i = LIndex; i <= UIndex; i++)
            {
                strReturn += tmStr[i] + strDelimiter;
            }

            return strReturn.Remove(strReturn.Length - 1);
        }
Example #31
0
 public static string strPick(string strData, string strDelimiter, PickOptions pickBegins, PickOptions pickDirection, int DelimiterInstance)
 {
     return strPick(strData, strDelimiter, pickBegins, pickDirection, DelimiterInstance, true);
 }
Example #32
0
 public static string strPick(string strData, string strDelimiter, PickOptions pickBegins, PickOptions pickDirection)
 {
     return strPick(strData, strDelimiter, pickBegins, pickDirection, 1, true);
 }
Example #33
0
 public static string strPick(string strData, string strDelimiter, PickOptions pickBegins)
 {
     return strPick(strData, strDelimiter, pickBegins, PickOptions.Reverse, 1, true);
 }
Example #34
0
 /// <include file="../../docs/Microsoft.Maui.Essentials/FilePicker.xml" path="//Member[@MemberName='PickMultipleAsync']/Docs" />
 public static Task <IEnumerable <FileResult> > PickMultipleAsync(PickOptions options = null) =>
 PlatformPickAsync(options ?? PickOptions.Default, true);