I need to save Image from Local Storage Folder to file selected from SavePicker.
Should I use stream?
Here is my code:
StorageFile file = await savePicker.PickSaveFileAsync();
if (null != file)
{
var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile current_photo = await localFolder.GetFileAsync(img.Tag.ToString());
// TODO Stream from current_photo to file
}
CopyAsync should do it:
await current_photo.CopyAndReplaceAsync(file);
Related
I'm using FileIO to append Json data in a LocalStorage file.
public static async Task AppendToJsonLocalStorage<T>(string filename, T objectToWrite) where T : new()
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile saveFile = await localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
await FileIO.AppendTextAsync(saveFile, contentsToWriteToFile);
}
AppendTextAsync should only add new text at the end of the existing file, wright ?
Because when I check the file in my file explorer with a text editor it's always overwriting the former text in it.
Use CreationCollisionOption.OpenIfExists instead of CreationCollisionOption.ReplaceExisting when you create the file:
StorageFile saveFile = await localFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
await FileIO.AppendTextAsync(saveFile, contentsToWriteToFile);
ReplaceExisting replaces any existing file as the name suggests. Please refer to the docs for more information.
I'm a newbie in UWP and i want to open a file of any type and transmit the bytes of it to the reciever. forexample for a jpg file i wrote this code:
// Create FileOpenPicker instance
FileOpenPicker fileOpenPicker = new FileOpenPicker();
// Set SuggestedStartLocation
fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
// Set ViewMode
fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;
fileOpenPicker.FileTypeFilter.Clear();
fileOpenPicker.FileTypeFilter.Add(".jpg");
// Open FileOpenPicker
StorageFile file = await fileOpenPicker.PickSingleFileAsync();
byte[] bytesRead = File.ReadAllBytes(file.Path);
string Paths =
#"C:\\Users\zahraesm\Pictures\sample_reconstructed.jpg";
File.WriteAllBytes(Paths, bytesRead);
the two last lines are for writing the bytes into a file supposing in the receiver. However i keep getting the following exception:
System.InvalidOperationException: 'Synchronous operations should not be performed on the UI thread. Consider wrapping this method in Task.Run.'
Try this Code.
try {
FileOpenPicker openPicker = new FileOpenPicker {
ViewMode = PickerViewMode.Thumbnail,
SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
FileTypeFilter = { ".jpg", ".jpeg", ".png" }
};
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null) {
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read)) {
var reader = new Windows.Storage.Streams.DataReader(fileStream.GetInputStreamAt(0));
var LoadReader = await reader.LoadAsync((uint)fileStream.Size);
byte[] pixels = new byte[fileStream.Size];
reader.ReadBytes(pixels);
}
}
} catch (Exception ex) {
}
consider wrapping last operation in Task.Run()
await Task.Run(()=>{
byte[] bytesRead = File.ReadAllBytes(file.Path);
string Paths =
#"C:\\Users\zahraesm\Pictures\sample_reconstructed.jpg";
File.WriteAllBytes(Paths, bytesRead);
});
You should directly read the bytes from the StorageFile returned from your FilePicker, lest you end up with File permission errors in the future.
StorageFile file = await fileOpenPicker.PickSingleFileAsync();
var buffer = await FileIO.ReadBufferAsync(file);
byte[] bytes = System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.ToArray(buffer);
You should also use await FileIO.WriteBytesAsync(targetFile, myBytes) to write.
Unless you have broadFileSystemAccess in your package Manifest, you should generally avoid using the System.IO API unless you know your application explicitly has permission to access files in that area (i.e., your application's local storage), and instead use Windows.Storage API's
Check MSDN for File Access Permissions for UWP apps for more information on file permissions.
And if you do use System.IO, always perform the work on the background thread via await Task.Run(() => { ... }
I want to open a text file with Open File Picker and show in a RichEditBox, but when I select the file and push Ok, Visual Studio show "Access Denied", I want to know how to solve this please, there is my code:
var picker = new FileOpenPicker();
picker.ViewMode = PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
picker.FileTypeFilter.Add("*");
picker.FileTypeFilter.Add(".txt");
picker.FileTypeFilter.Add(".text");
picker.FileTypeFilter.Add(".bat");
picker.FileTypeFilter.Add(".js");
picker.FileTypeFilter.Add(".vbs");
StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile filepath = await StorageFile.GetFileFromPathAsync(file.Path);
string text = await FileIO.ReadTextAsync(filepath);
RichEditBox1.Document.SetText(Windows.UI.Text.TextSetOptions.None, text);
}
You don't need to call StorageFile.GetFileFromPathAsync(file.Path) since you already have this StorageFile in the file variable returned from PickSingleFileAsync:
StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
string text = await FileIO.ReadTextAsync(file);
RichEditBox1.Document.SetText(Windows.UI.Text.TextSetOptions.None, text);
}
The unnecessary GetFileFromPathAsync probably throws an AccessDenied error since the FileOpenPicker provides access only through the returned StorageFile and doesn't give direct access to the file through its path. This behavior is version dependent and new versions of Windows 10 will allow more direct access through file system API (see the Build 2017 talk UWP Apps file access improvements
In my windows phone application i'm trying to create a new contact and add an image that taken from the camera, but it didn't seems to work.
No matter what i do the photo is blank.
The only way it works for me is by using an image that i added in the assets folder (and not from camera), even trying to add the image to the local assets folder and then to upload it - don't work...
(there is no error, but the contact that was added don't have a photo).
await contact.SetDisplayPictureAsync(stream.AsStream().AsInputStream());
Here is my code:
when i get the selected image from store i save it to a bitmapImage and use its pixel buffer.
public async void AddContact(string displayName, string mobile, string email, byte[] data)
{
var store = await ContactStore.CreateOrOpenAsync();
var contact = new StoredContact(store)
{
DisplayName = displayName
};
var props = await contact.GetPropertiesAsync();
props.Add(KnownContactProperties.Email, email);
props.Add(KnownContactProperties.MobileTelephone, mobile);
using (var stream = bitmap.PixelBuffer.AsStream())
{
await contact.SetDisplayPictureAsync(stream.AsInputStream());
}
await contact.SaveAsync();
}
Please help!
I was doing the same to set profile picture in for contact and it was not working. But when I get IRandomAccessStream from storage file it worked here is what I am doing
var file = await folder.GetFileAsync("filename.jpeg"));
//Or you can get file direclty from localfolder
// var file = await ApplicationData.Current.LocalFolder.GetFileAsync("filename.jpeg");
using (Windows.Storage.Streams.IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
await contact.SetDisplayPictureAsync(fileStream);
}
await contact.SaveAsync();
Edit
How to Save picture to local storage using media capture.
ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();
//Save file to local storage
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
"MyPhoto.jpg", CreationCollisionOption.ReplaceExisting);
await mediaCapture.CapturePhotoToStorageFileAsync(imgFormat, file);
Once the image is saved in local storage you can get that image from me first example
Edit 2
If you are using File open picker you can try this.
public async void ContinueFileOpenPicker(Windows.ApplicationModel.Activation.FileOpenPickerContinuationEventArgs args)
{
if (args.Files.Count > 0)
{
var filePath = args.Files[0].Path;
StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(filePath);
using (Windows.Storage.Streams.IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
await contact.SetDisplayPictureAsync(fileStream);
}
}
I have created local folder for downloading files using followling code
StorageFile destinationFile;
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
var dataFolder = await local.CreateFolderAsync("AppDownloads",
CreationCollisionOption.OpenIfExists);
destinationFile = await dataFolder.CreateFileAsync(destination,
CreationCollisionOption.GenerateUniqueName);
Now i need to access all downloaded files from the sub folder created.
I have tried using:
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
IStorageFolder dataFolder1 = await local.GetFolderAsync("AppDownloads");
IEnumerable<IStorageFile> files = await local.GetFilesAsync();
But this is not working.How to get all downloaded files from this folder ?
Thank you.