Csharp/C#教程:在Windows Universal中将文件写入外部闪存驱动器分享


在Windows Universal中将文件写入外部闪存驱动器

我在Raspberry PI上使用Windows IoT编写应用程序。 我想将数据写入连接到其中一个USB端口的外部闪存驱动器。 我已经找到了如何在PI中写入SD卡的示例,但最终产品中无法访问SD卡。

我可以获取闪存驱动器的根文件夹名称,但是当我尝试向其写入文件时,我收到了拒绝访问的消息。 如果我切换到SD卡一切正常。

有人能指出一个允许访问外部闪存驱动器的示例吗?

出于安全原因,Universal Windows Applications只能访问外部驱动器上的某些类型的文件,

您必须在Package.appxmanifest文件中明确声明它。

您可能还想检查可移动存储function。

我不认为您可以访问除上述三种类型之外的常规文件格式,否则您将获得“访问被拒绝”exception。

在此处查找更多详细信息。

声明了您的function后,您可以使用以下代码获取外部存储设备的根文件夹,

var removableDevices = KnownFolders.RemovableDevices; var externalDrives = await removableDevices.GetFoldersAsync(); var drive0 = externalDrives[0]; 

然后,您可以使用Stream方法写入文件,遵循此处的代码示例。

如果要将数据写入通用文件格式,解决方法是使用可访问的文件格式(如jpg),并将原始数据写入其中。 下面是一些在Raspberry Pi 2 Model B上validation的代码示例,使用Windows IoT 14393,外部USB驱动器连接到USB端口。

  private async void WriteData() { var removableDevices = KnownFolders.RemovableDevices; var externalDrives = await removableDevices.GetFoldersAsync(); var drive0 = externalDrives[0]; var testFolder = await drive0.CreateFolderAsync("Test"); var testFile = await testFolder.CreateFileAsync("Test.jpg"); var byteArray = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; using (var sourceStream = new MemoryStream(byteArray).AsRandomAccessStream()) { using (var destinationStream = (await testFile.OpenAsync(FileAccessMode.ReadWrite)).GetOutputStreamAt(0)) { await RandomAccessStream.CopyAndCloseAsync(sourceStream, destinationStream); } } } 

在Package.appxmanifest文件中设置function

上述就是C#学习教程:在Windows Universal中将文件写入外部闪存驱动器分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

              

 private async void btnCopyImages_Click(object sender, RoutedEventArgs e) { // Get the logical root folder for all external storage devices. StorageFolder externalDevices = Windows.Storage.KnownFolders.RemovableDevices; // Get the first child folder, which represents the SD card. StorageFolder sdCard = (await externalDevices.GetFoldersAsync()).FirstOrDefault(); // An SD card is present and the sdCard variable now contains a to reference it. if (sdCard != null) { StorageFile resultfile = await sdCard.CreateFileAsync("foo.png", CreationCollisionOption.GenerateUniqueName); string base64 = "/9j/4AAQSkZJRgABAQEAYABgAAD/4RjqR.....; var bytes = Convert.FromBase64String(base64); await FileIO.WriteBytesAsync(resultfile, bytes); } // No SD card is present. else { } } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1034136.html

(0)
上一篇 2022年1月18日
下一篇 2022年1月18日

精彩推荐