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

587 views Asked by At

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.'

3

There are 3 answers

0
Mohanvel V On

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) {

        }
0
Muhammad Touseef On

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); 
});
0
Johnny Westlake On

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