[英]Writing files to external flash drive in Windows Universal
我正在Raspberry PI上使用Windows IoT編寫應用程序。 我想將數據寫入連接到USB端口之一的外部閃存驅動器。 我已經找到了有關如何在PI中寫入SD卡的示例,但是在最終產品中將無法訪問SD卡。
我可以獲取閃存驅動器的根文件夾名稱,但是當我嘗試向其中寫入文件時,會收到訪問被拒絕的消息。 如果我切換到SD卡,則一切正常。
誰能指出一個允許訪問外部閃存驅動器的示例?
在Package.appxmanifest文件中設置功能
<Capabilities>
<Capability Name="internetClient" />
<uap:Capability Name="removableStorage" />
<!--When the device's classId is FF * *, there is a predefined name for the class.
You can use the name instead of the class id.
There are also other predefined names that correspond to a classId.-->
<DeviceCapability Name="usb">
<!--SuperMutt Device-->
<Device Id="vidpid:045E 0611">
<!--<wb:Function Type="classId:ff * *"/>-->
<Function Type="name:vendorSpecific" />
</Device>
</DeviceCapability>
</Capabilities>
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
{
}
}
出於安全原因,通用Windows應用程序只能訪問外部驅動器上的某些類型的文件,
並且您必須在Package.appxmanifest文件中明確聲明它。
您可能還需要檢查可移動存儲功能。
除上述三種類型外,我認為您無法訪問常規文件格式,否則會出現“訪問被拒絕”異常。
在這里找到更多詳細信息。
聲明功能后,可以使用以下代碼獲取外部存儲設備的根文件夾,
var removableDevices = KnownFolders.RemovableDevices;
var externalDrives = await removableDevices.GetFoldersAsync();
var drive0 = externalDrives[0];
然后,您可以按照此處的代碼示例,使用Stream方法寫入文件。
如果要將數據寫入通用文件格式,一種解決方法是使用可訪問的文件格式(如jpg),然后將原始數據寫入其中。 以下是一些代碼示例,已在具有Windows IoT 14393的Raspberry Pi 2 Model B上進行了驗證,並且外部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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.