Newbie question here. I have this file picker:
public async void PickImage()
{
FileOpenPicker ImagePicker = new FileOpenPicker();
...
StorageFile file = await ImagePicker.PickSingleFileAsync(); //
...
}
And I want to use the file set by this image picker in another method. Something like this:
private async void CreateButton_Click(object sender, RoutedEventArgs e)
{
... the one from PickImage()
v
StorageFile copyImage = await file.CopyAsync(DateTimeFolder, "image", NameCollisionOption.ReplaceExisting);
...
}
It is obviously not working like this. How can I do it?
Ok, based on the answers I got, this is what I came up with:
public async Task<StorageFile> PickImage()
{
FileOpenPicker ImagePicker = new FileOpenPicker();
ImagePicker.FileTypeFilter.Add(".jpg");
ImagePicker.FileTypeFilter.Add(".jpeg");
ImagePicker.FileTypeFilter.Add(".png");
ImagePicker.ViewMode = PickerViewMode.Thumbnail;
ImagePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
StorageFile file = await ImagePicker.PickSingleFileAsync();
if (file != null)
{
IRandomAccessStream imageStream = await file.OpenAsync(FileAccessMode.Read);
var bmpImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
bmpImage.DecodePixelHeight = 150;
bmpImage.DecodePixelWidth = 310;
bmpImage.SetSource(imageStream);
ImagePreview.Source = bmpImage;
}
return file;
}
////
private async void CreateButton_Click(object sender, RoutedEventArgs e)
{
...
string DateTimeNow = DateTime.Now.ToString("HHmmssddMMyyyy");
StorageFolder docs = KnownFolders.DocumentsLibrary;
StorageFolder myDir = await docs.CreateFolderAsync("My Dir", Windows.Storage.CreationCollisionOption.OpenIfExists);
StorageFolder DateTimeFolder = await myDir.CreateFolderAsync(DateTimeNow);
//StorageFile image = await PickImage();
StorageFile copyImage = await PickImage().CopyAsync(DateTimeFolder, "image", NameCollisionOption.ReplaceExisting);
...
}
But the last line gives me an error:
'System.Threading.Tasks.Task' does not contain a definition for 'CopyAsync' and no extension method 'CopyAsync' accepting a first argument of type 'System.Threading.Tasks.Task' could be found (are you missing a using directive or an assembly reference?)
You need to either set a field in the class or return the StorageFile. I would suggest changing PickImage() to return the StorageFile so you're code would instead look like this;
public async StorageFile PickImage()
{
FileOpenPicker ImagePicker = new FileOpenPicker();
...
return await ImagePicker.PickSingleFileAsync(); //
...
}
private async void CreateButton_Click(object sender, RoutedEventArgs e)
{
StorageFile pickedFile = await PickImage();
StorageFile copyImage = await file.CopyAsync(DateTimeFolder, "image", NameCollisionOption.ReplaceExisting);
...
}
Or something to that effect. I'm slightly confused by the second line in your CreateButton_Click method because I thought you wanted to operate on the file from PickImage but instead you're creating a new file. If you want the StorageFile to persist just make it a field on the form class and set it in PickImage
As pointed by Andre in the comments, your PickImage should return the file, so you could do the following:
public async StorageFile PickImage()
{
FileOpenPicker ImagePicker = new FileOpenPicker();
...
StorageFile file = await ImagePicker.PickSingleFileAsync(); //
...
return file;
}
private async void CreateButton_Click(object sender, RoutedEventArgs e)
{
...
StorageFile copyImage = await this.PickImage().CopyAsync(DateTimeFolder, "image", NameCollisionOption.ReplaceExisting);
...
}
Depending on the location of the two methods, there are two solutions:
If the methods are located in the same class file, you can declare StorageFile file as a local variable in the class file. In that way, you can reach it from the CreateButton_click function
If cross threading is involved (methods are working in separate threads), you need to use delegates and invoke them. Detailed information is available here through an example.
Related
I am trying to display an list in an listview in Visual Studio that was first serialized and then deserialized. Everything works fine but my problem is that the list is displayed in an very weird format you can see it in the picture below.
Heres my code so far:
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
KalenderClass k1 = new KalenderClass();
k1.termin = TerminTextbox.Text;
k1.datum = DatePicker1.Date;
k1.person = PersonTextbox.Text;
kList.Add(k1);
SaveData(kList);
}
private async void SaveData(List<KalenderClass> kList)
{
StorageFolder ordner = ApplicationData.Current.LocalFolder;
StorageFile datei = await ordner.CreateFileAsync("Kalender.txt", CreationCollisionOption.OpenIfExists);
await FileIO.WriteTextAsync(datei, JsonConvert.SerializeObject(kList));
showDialog("Daten wurden in Datei geschrieben");
}
private async void ReadButton_Click(object sender, RoutedEventArgs e)
{
StorageFolder ordner = Windows.Storage.ApplicationData.Current.LocalFolder;
string path = ordner.Path;
StorageFile datei = await ordner.GetFileAsync("Kalender.txt");
string inhalt = await FileIO.ReadTextAsync(datei);
var k = JsonConvert.DeserializeObject(inhalt);
TerminListview.Items.Add(k);
}
I dont want to add the whole List k to the listview but just the new object.
And here is the way it is displayed:
I want it to be a format, for example:
Termin 1:
Date:
Person:
I hope you guys can help me
Change CreationCollisionOption from:
CreationCollisionOption.OpenIfExists
To:
CreationCollisionOption.ReplaceExisting
Or you can refresh the list inside the SaveButton_Click method as the following:
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
kList = new List<KalenderClass>(); // <== This line will reset the list
KalenderClass k1 = new KalenderClass();
k1.termin = TerminTextbox.Text;
k1.datum = DatePicker1.Date;
k1.person = PersonTextbox.Text;
kList.Add(k1);
SaveData(kList);
}
private void Gallery_Click(object sender, object e)
{
view = CoreApplication.GetCurrentView();
var filePicker = new FileOpenPicker
{
SuggestedStartLocation = PickerLocationId.PicturesLibrary,
ViewMode = PickerViewMode.Thumbnail
};
// Filter to include a sample subset of file types
filePicker.FileTypeFilter.Clear();
filePicker.FileTypeFilter.Add(".bmp");
filePicker.FileTypeFilter.Add(".png");
filePicker.FileTypeFilter.Add(".jpeg");
filePicker.FileTypeFilter.Add(".jpg");
mediaCapture.StopPreviewAsync();
filePicker.PickSingleFileAndContinue();
view.Activated += ViewActivated;
}
private async void ViewActivated(CoreApplicationView sender, IActivatedEventArgs args)
{
var arguments = args as FileOpenPickerContinuationEventArgs;
if (arguments != null && arguments.Files.Count != 0)
{
view.Activated -= ViewActivated;
var storageFile = arguments.Files[0];
var file =
await
ApplicationData.Current.LocalFolder.CreateFileAsync("Photo.jpg",
CreationCollisionOption.GenerateUniqueName);
await storageFile.CopyAndReplaceAsync(file);
var bmpImage = new BitmapImage(new Uri(file.Path));
UseThePhoto(bmpImage);
}
else
await mediaCapture.StartPreviewAsync();
}
I have this code above. When I choose an image from a gallery I can use it in an Image control that is on the same page. However, if I want to navigate to any other page, I get an error. No details from it. The code ends in App.g.i.cs
Problem solved. I was using not the blank page template but the basic page. And for some reason the method OnNavigatedFrom invoked this error so i created an override and let it empty, so it couldn't call the navigation helper class.
I am trying to import music files from your pc to make your own playlist.
code below:
public async void Button_Click(object sender, RoutedEventArgs e) // Pick directory
{
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.FileTypeFilter.Add(".wmv");
openPicker.FileTypeFilter.Add(".mp4");
openPicker.FileTypeFilter.Add(".wma");
openPicker.FileTypeFilter.Add(".mp3");
var file = await openPicker.PickSingleFileAsync();
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
// media is a MediaElement defined in XAML
if (null != file)
{
media.SetSource(stream, file.ContentType);
media.Play();
}
}
private async void Button_Click_1(object sender, RoutedEventArgs e) //Import file
{
this.Frame.Navigate(typeof(importedfile));
importedfile import = new importedfile(); // The imported file goes to that page.
//What do I do to get the imported file into a new grid (Picture below
}
For example: I Import a song and I hit the import button it will navigate me to the importedfile page but what do I do next?.
I want to workk with an image picked by file picker in windows phone 8.1.I picked an image using this code
private async void gallery_Tapped(object sender, TappedRoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
// Launch file open picker and caller app is suspended and may be terminated if required
openPicker.PickSingleFileAndContinue();
}
public async void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args)
{
if (args.Files.Count > 0)
{
StorageFile file=args.Files[0];
IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(fileStream);
MyImage.Source=bitmapImage;
}
else
{
}
}
ContinueFileOpenPicker not executing I tried this but unable to understand that.Can any here guide me step by step what should I do to make it work.Thanks
protected override void OnActivated(IActivatedEventArgs args)
{
var root = Window.Current.Content as Frame;
var mainPage = root.Content as MainPage;
if (mainPage != null && args is FileOpenPickerContinuationEventArgs)
{
mainPage.ContinueFileOpenPicker(args as FileOpenPickerContinuationEventArgs);
}
}
Put this code in app.xaml.cs it will work..
I have been following this tutorial http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj681698%28v=vs.105%29.aspx.
So far is what I was searching for, but the only problem is that when i close and open the app again the file and the text is not saved anymore, so I want to the file be saved forever with the text.
I want to it be saved here http://gyazo.com/82e838cd2385cea7021647a8d39f49a8.png/level/batlevel.txt. So when I can open the app again the text that was write there it will be there
private async void btnWrite_Click(object sender, RoutedEventArgs e)
{
await WriteToFile();
// Update UI.
this.btnWrite.IsEnabled = false;
this.btnRead.IsEnabled = true;
}
private async Task WriteToFile()
{
// Get the text data from the textbox.
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(this.textBox1.Text.ToCharArray());
// Get the local folder.
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
// Create a new folder name DataFolder.
var dataFolder = await local.CreateFolderAsync("level",
CreationCollisionOption.OpenIfExists);
// Create a new file named DataFile.txt.
var file = await dataFolder.CreateFileAsync("level.txt",
CreationCollisionOption.ReplaceExisting);
// Write the data from the textbox.
using (var s = await file.OpenStreamForWriteAsync())
{
s.Write(fileBytes, 0, fileBytes.Length);
}
}
private async void btnRead_Click(object sender, RoutedEventArgs e)
{
await ReadFile();
// Update UI.
this.btnWrite.IsEnabled = true;
this.btnRead.IsEnabled = false;
}
private async Task ReadFile()
{
// Get the local folder.
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
if (local != null)
{
// Get the DataFolder folder.
var dataFolder = await local.GetFolderAsync("level");
// Get the file.
var file = await dataFolder.OpenStreamForReadAsync("level.txt");
// Read the data.
using (StreamReader streamReader = new StreamReader(file))
{
this.textBlock1.Text = streamReader.ReadToEnd();
}
}
}
}
}
I believe you should be opening your level.txt file with the OpenIfExists option instead of ReplaceExisting :
// Create a new file named DataFile.txt.
var file = await dataFolder.CreateFileAsync( "level.txt", CreationCollisionOption.OpenIfExists );