Skip to content

Instantly share code, notes, and snippets.

@skendrot
Created July 1, 2015 19:23
Show Gist options
  • Save skendrot/d497d938ec96a08f3bf0 to your computer and use it in GitHub Desktop.
Save skendrot/d497d938ec96a08f3bf0 to your computer and use it in GitHub Desktop.
Simpler FilePicker
using System;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.Core;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
namespace Pinnacle.Pickers
{
public class FilePicker
{
private TaskCompletionSource<IRandomAccessStream> _imageCompletionSource;
private IEnumerable<string> _fileTypes;
public FilePicker(IEnumerable<string> fileTypes)
{
_fileTypes = fileTypes;
}
#if WINDOWS_PHONE_APP
public Task<IRandomAccessStream> PickAsync()
#else
public async Task<IRandomAccessStream> PickAsync()
#endif
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
foreach(var type in _fileTypes)
{
openPicker.FileTypeFilter.Add(type);
}
#if WINDOWS_PHONE_APP
_imageCompletionSource = new TaskCompletionSource<IRandomAccessStream>();
CoreApplication.GetCurrentView().Activated += OnViewActivated;
openPicker.PickSingleFileAndContinue();
return _imageCompletionSource.Task;
#else
StorageFile storageFile = await openPicker.PickSingleFileAsync();
return await storageFile.OpenAsync(FileAccessMode.Read);
#endif
}
private async void OnViewActivated(CoreApplicationView sender, IActivatedEventArgs args)
{
sender.Activated -= OnViewActivated;
FileOpenPickerContinuationEventArgs pickerArgs = args as FileOpenPickerContinuationEventArgs;
IRandomAccessStream stream = null;
if (pickerArgs != null)
{
if (pickerArgs.Files.Count > 0)
{
StorageFile storageFile = pickerArgs.Files[0];
stream = await storageFile.OpenAsync(FileAccessMode.Read);
}
}
_imageCompletionSource.SetResult(stream);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment