如何获取文件的字节以在UWP中发送?

时间:2018-10-02 11:29:28

标签: c# uwp uwp-xaml fileopenpicker

我是UWP的新手,我想打开任何类型的文件并将其字节发送给接收者。例如我写了一个jpg文件的代码:

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

最后两行用于将字节写入假定在接收方的文件中。但是我一直收到以下异常:

  

System.InvalidOperationException:'不应在UI线程上执行同步操作。考虑将此方法包装在Task.Run中。”

3 个答案:

答案 0 :(得分:1)

尝试此代码。

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

        }

答案 1 :(得分:0)

考虑将最后一个操作包装在 Task.Run()

await Task.Run(()=>{
    byte[] bytesRead = File.ReadAllBytes(file.Path);        
    string  Paths = 
    @"C:\\Users\zahraesm\Pictures\sample_reconstructed.jpg";
    File.WriteAllBytes(Paths, bytesRead); 
});

答案 2 :(得分:0)

您应该直接从FilePicker返回的StorageFile中读取字节,以免将来遇到文件许可权错误。

if (!PKAddPaymentPassViewController.canAddPaymentPass()){
        print("not enabled")
    }
    let config = PKAddPaymentPassRequestConfiguration.init(encryptionScheme: PKEncryptionScheme.ECC_V2)

    guard let addPaymentPassVC = PKAddPaymentPassViewController.init(requestConfiguration: config!, delegate: self) else { return }

    self.present(addPaymentPassVC, animated: true, completion: nil)

您还应该使用StorageFile file = await fileOpenPicker.PickSingleFileAsync(); var buffer = await FileIO.ReadBufferAsync(file); byte[] bytes = System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.ToArray(buffer); 进行书写。

除非您的软件包清单中有await FileIO.WriteBytesAsync(targetFile, myBytes),否则通常应该避免使用broadFileSystemAccess API,除非您知道应用程序明确有权访问该区域中的文件(即应用程序的本地存储) ,而是使用System.IO API的

在MSDN中检查File Access Permissions for UWP apps,以获取有关文件权限的更多信息。

如果您确实使用Windows.Storage,请始终通过System.IO在后​​台线程上执行工作