I am now a student studying win10 application development using csharp and xaml, recently when i try to to choose an image in my code and later replace an existing image in my local folder, an System.UnauthorizedAccessException occurred. It's very confusing because i am able to modify the image file in my localfolder when i create it for the first time, but after navigating to another page and then back to this page to modify it again, it doesn't work! Can someone help me with this problem?
private async void select_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker picker = new FileOpenPicker();
picker.ViewMode = PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
picker.FileTypeFilter.Add(".bmp");
StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);
BitmapImage pic = new BitmapImage();
pic.SetSource(stream);
this.head.Source = pic;
StorageFolder storageFolder =
ApplicationData.Current.LocalFolder;
StorageFile sampleFile =
await storageFolder.CreateFileAsync(PlayerName.Text + ".jpg", CreationCollisionOption.ReplaceExisting);
await file.CopyAndReplaceAsync(sampleFile);
//await file.CopyAsync(ApplicationData.Current.LocalFolder, PlayerName.Text + ".jpg", NameCollisionOption.ReplaceExisting);
Related
This is the code i have so far that that opens the picture and tries to save it
any information on why it's not working would be great thanks.
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation =PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation =
PickerLocationId.PicturesLibrary;
savePicker.FileTypeChoices.Add("jpeg image", new List<string>()
{ ".jpg" });
savePicker.SuggestedFileName = "Photo";
string token = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file);
StorageFile SaveFile = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(token);
StorageFile savefile = await savePicker.PickSaveFileAsync();
if (SaveFile != null)
{
await FileIO.WriteTextAsync(SaveFile, SaveFile.Name);
}
}
You store the opened file into FutureAccessList and then immediately retrieve it as SaveFile variable. Right below you create a saveFile which I guess is what you wanted to use, but in the WriteTextAsync method you pass SaveFile as the target, not saveFile.
You should definitely improve your naming convention, having two variables differing only in casing is very error prone. Furthermore, local variables should always start with lowercase letter.
I develop an uwp app in c# / xaml.
In my app I use this code for select an image in picture folder and put the image on the background of a grid:
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".png");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
var image = new BitmapImage();
ImageBrush ib = new ImageBrush();
ib.ImageSource = image;
image.SetSource(stream);
set.Background = new ImageBrush { ImageSource = image, Stretch = Stretch.UniformToFill };
}
else
{
//
}
and what I want to do is: save the image location in application setting for later re-use
And I don't know how to do...
Don't save path to the file in UWP - the app also needs privileges, not only file location. You will likely get UnauthorizedAccessException when you get file directly from path - for example C:\Images\image.jpg.
There are two lists in UWP to remeber StorageItems, along with privileges: FutureAccessList and MostRecentlyUsedList.
When you add an item to such list, you obtain a token and this is what you should remember in your LocalSettings (for example). Then you can reuse such token to access the file/folder. Sample:
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
// to save the token for further access
ApplicationData.Current.LocalSettings.Values["MyToken"] = StorageApplicationPermissions.FutureAccessList.Add(file);
// rest of the code
}
// to get the file later:
StorageFile theFile = await StorageApplicationPermissions.FutureAccessList.GetFileAsync((string)ApplicationData.Current.LocalSettings.Values["MyToken"]);
You can use the Windows.Storage.ApplicationDataContainer in following way:
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
localSettings.Values["some key"] = "your value"; // Store value in settings
var valueFromSettings = localSettings.Values["some key"]; // Getting value from settings
That way you can store and retrieve the file path, to get the path:
var filePath = file.Path;
and to get a StorageFile from a path:
var file = await StorageFile.GetFileFromPathAsync(filePath);
Is there a way I can get the image as Stream and then store it locally to upload it to server?
So far I found the code below which lets me load the image to an image view , but how do I create a stream from the image source to pass it to SaveToLocalFolderAsync method?
private async void viewActivated(CoreApplicationView sender, IActivatedEventArgs args1)
{
FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs;
if (args != null)
{
if (args.Files.Count == 0) return;
view.Activated -= viewActivated;
StorageFile storageFile = args.Files[0];
var stream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
await bitmapImage.SetSourceAsync(stream);
var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
imgCover.Source = bitmapImage;
//save the image in local folder
//SaveToLocalFolderAsync(stream, "Test.jpg");
}
}
public async Task SaveToLocalFolderAsync(Stream file, string fileName)
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (Stream outputStream = await storageFile.OpenStreamForWriteAsync())
{
await file.CopyToAsync(outputStream);
}
}
In my windows app, i am trying to load an image from local machine to server but facing an exception of System.Runtime.InteropServices.COMException on the statement StorageFile file = await open.PickSingleFileAsync();. Here is the method:
FileOpenPicker open = new FileOpenPicker();
StorageFile file = await open.PickSingleFileAsync();
if (file != null)
{
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.DecodePixelWidth = 600; //match the target Image.Width, not shown
await bitmapImage.SetSourceAsync(fileStream);
big_image.Source = bitmapImage;
}
}
How to fix it ??? I am using VS '13. Big_image is the image defined in xaml and i am trying to set its source.
i got the solution by adding some new stuff:
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
big_image.Source = bitmapImage;
}
}
microsoft.phone.tasks.photochoosertask is used to pick images.
In my app user can set profile pic from device memory i.e tablet memory or desktop local drive and upload it to server.
I used file picker so that user can select one picture and set it as profile picture, but the problem is the picture is not sticking to Image element.
My code:
private async void filePicker()
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
String filePath = file.Path;
System.Diagnostics.Debug.WriteLine(filePath);
Uri uri = new Uri(filePath, UriKind.Relative);
profilePicture.Source = new BitmapImage(uri);
}
}
internal bool EnsureUnsnapped()
{
// FilePicker APIs will not work if the application is in a snapped state.
// If an app wants to show a FilePicker while snapped, it must attempt to unsnap first
bool unsnapped = ((ApplicationView.Value != ApplicationViewState.Snapped) || ApplicationView.TryUnsnap());
if (!unsnapped)
{
//NotifyUser("Cannot unsnap the sample.", NotifyType.StatusMessage);
}
return unsnapped;
}
the file path that I'm getting is this one
filePath=C:\Users\Prateek\Pictures\IMG_0137.JPG
I don't know what went wrong.
I am not sure if this will solve the problem, this is what I did to set my image source.
Using a bitmap image as the source to your image
BitmapImage bitmapimage = new BitmapImage();
StorageFile file = await openPicker.PickSingleFileAsync();
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
await bitmapimage.SetSourceAsync(stream);
profilePicture.Source = bitmapImage;
I have used this code ...
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
this.textBlock.Text =
"File Path: " + file.Path + Environment.NewLine +
"File Name: " + file.Name;
try
{
var stream = await file.OpenReadAsync();
var imageSource = new BitmapImage();
await imageSource.SetSourceAsync(stream);
this.image.Source = imageSource;
}
catch (Exception ex)
{
this.textBlock.Text = ex.ToString();
}
}
else
{
this.textBlock.Text = "Operation cancelled.";
}