how to get Bytes of a file for sending in UWP? - c#

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(() => { ... }

Related

Access to the path, when try to ReadAllTheBytes [duplicate]

This question already has an answer here:
UWP, Access to the path is denied
(1 answer)
Closed 3 years ago.
I am getting a file, via a picker and I am displaying that image in a Image control in xaml.
The image displays perfectly, but when I tried to convert the path to bytes, I get the error
Tried to give picture library permition
var picker = new FileOpenPicker();
picker.ViewMode = PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".png");
picker.FileTypeFilter.Add(".jpeg");
var file = await picker.PickSingleFileAsync();
if (file != null) {
var stream = await file.OpenReadAsync();
var bitmap = new BitmapImage();
bitmap.SetSource(stream);
var bytes = File.ReadAllBytes(file.Path); // Error
selectedimage.Source = bitmap;
{"Access to the path 'some path' is denied."}
Access to the path, when try to ReadAllTheBytes
UWP run in sandbox, we can't access the file with the path directly,Even though we already add broadFileSystemAccess capability, we could not use ReadAllTheBytes under System.IO namespace. And Pavel Anikhouski's comment is correct, we could use MemoryStream to convert the file to bytes.
byte[] result;
using (Stream stream = await imageFile.OpenStreamForReadAsync())
{
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
result = memoryStream.ToArray();
}
}

xamarin.forms save file/image

coding xamarin form project and also using pcl storage. have problem with saving image or file on device all examples i found show how to save stream of byte array into file but non of them show how to turn convert image into usable format for saving.
var webImage = new Image();
webImage.Source = new UriImageSource
{
CachingEnabled = false,
Uri = new Uri("http://server.com/image.jpg"),
};
byte[] image = ????(what i need)????(webImage.Source);
// get hold of the file system
IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage;
// create a file, overwriting any existing file
IFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
// populate the file with image data
using (System.IO.Stream stream = await file.OpenAsync(FileAccess.ReadAndWrite))
{
stream.Write(image, 0, image.Length);
}
In other words looking for code to save image/file on device from url.
Tried ffimageloading since it contain converter to byte[], but always get error:"Object reference not set to an instance of an object." for GetImageAsJpgAsync and GetImageAsPngAsync method. problem might be that image isn't fully loaded. but finish event and finish command never get called even trough image is fully loaded on screen and bound to cachedImage.
var cachedImage = new CachedImage()
{
Source = "https://something.jpg",
FinishCommand = new Command(async () => await TEST()),
};
cachedImage.Finish += CachedImage_Finish;
var image = await cachedImage.GetImageAsJpgAsync();
With FFImageLoading (I noticed you use it):
await ImageService.Instance.LoadUrl("https://something.jpg").AsJpegStream();
If you want to get original file location, use this:
await ImageService.Instance.LoadUrl("https://something.jpg").Success((imageInfo) => { //TODO imageInfo.FilePath } ).DownloadOnly();

UWP - How to Save a Contact Thumbnail to Local Storage?

i want some help to get the thumbnail image of a Contact and save it to Local Storage, i successfully got the contact Thumbnail but i can't get the actual image from the stream, this is my Code:
var contactStore = await ContactManager.RequestStoreAsync();
var contacts = await contactStore.FindContactsAsync();
var myContact = contacts[0]; //I am sure that this Contact has a Thumbnail
var stream = await myContact.Thumbnail.OpenReadAsync();
byte[] buffer = new byte[stream.Size];
var readBuffer = await stream.ReadAsync(buffer.AsBuffer(), (uint)buffer.Length, InputStreamOptions.None);
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("image.jpg", CreationCollisionOption.ReplaceExisting);
var fileStream = await file.OpenStreamForWriteAsync();
await fileStream.WriteAsync(readBuffer.ToArray(), 0, (int)readBuffer.Length);
this code creates an empty image in the local storage, any help ?
thanks for your time
The problem here is that you missed Stream.Flush method to flush the buffer to the underlying stream. You can add fileStream.Flush(); after fileStream.WriteAsync method to fix your issue.
Besides this, we also need to call Stream.Dispose Method to releases the resources used by the Stream when we finish using it. And this method disposes the stream, by writing any changes to the backing store and closing the stream to release resources. So we can just use fileStream.Dispose() after fileStream.WriteAsync method.
A recommend way to call the Dispose method is using the C# using statement like following:
var contactStore = await ContactManager.RequestStoreAsync();
var contacts = await contactStore.FindContactsAsync();
var myContact = contacts[0]; //I am sure that this Contact has a Thumbnail
using (var stream = await myContact.Thumbnail.OpenReadAsync())
{
byte[] buffer = new byte[stream.Size];
var readBuffer = await stream.ReadAsync(buffer.AsBuffer(), (uint)buffer.Length, InputStreamOptions.None);
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("image.jpg", CreationCollisionOption.ReplaceExisting);
using (var fileStream = await file.OpenStreamForWriteAsync())
{
await fileStream.WriteAsync(readBuffer.ToArray(), 0, (int)readBuffer.Length);
}
}
I believe you may have to call stream.Dispose() after you read from it or else initialize the stream with a using directive: using (var outputStream = stream.GetOutputStreamAt(0))
The following link might be useful:
https://msdn.microsoft.com/en-us/windows/uwp/files/quickstart-reading-and-writing-files?f=255&MSPPError=-2147217396

Add photo from library to contact in wp8.1

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);
}
}

Copy or open external file in windows RT app

I would like to show a pdf from a website in my windows rt app (for Desktops with windows 8). How can I handle this?
If I add the file manually to the asset I can display it. But how can I do this with files where are not located on my asset Folder?
Can I copy the file to the StorageFolder?
Or can I directly open the file from the website?
Please give me some hints how I can solve this.
THX
To open files from you application you use Launcher in Windows 8 Applications. Refer the MSDN LINK: http://msdn.microsoft.com/en-in/library/windows/apps/hh701465.aspx and http://www.codeguru.com/win_mobile/win_store_apps/launching-files-with-associated-programs-in-windows-8.x-and-vb.htm
Hi I want to open it in my app and I not want to use the launcher.
I copy the file with HttpWebRequest to LocalFolder and process the pdf. I've solved it this way:
StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile file = null;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(filepath);
//TODO Systemuser
request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
var response = await request.GetResponseAsync();
List<Byte> allBytes = new List<byte>();
using (Stream imageStream = response.GetResponseStream()) {
byte[] buffer = new byte[4000];
int bytesRead = 0;
while ((bytesRead = await imageStream.ReadAsync(buffer, 0, 4000)) > 0) {
allBytes.AddRange(buffer.Take(bytesRead));
}
}
file = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(file, allBytes.ToArray());
await RenderPDFPage(fileName);

Categories