Přístup k souborovému systému v UWP je z důvodu bezpečnosti omezený. Ani s deklarovanou broadFileSystemAccess
capability nemohou obecně API mimo Windows.Storage
přistupovat k souborům přes jejich cestu. Naštěstí většina knihoven nabízí přetížené varianty metod s parametrem System.IO.Stream
, pomocí kterých se lze problému snadno vyhnout. Ale jak dostat Stream
z našeho StorageFile
? To stále úspěšně zapomínám, takže doufám, že mi to tento článek pomůže zapamatovat 😀 .
Konverzní metody přímo na StorageFile
nenajdeme. Jsou však dostupné jako extension metody v typu WindowsRuntimeStorageExtensions
, který najdeme v namespace System.IO
. Nejprve tedy musíme do našeho C# souboru přidat direktivu using
:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IO; |
A teď už můžeme volat metodu OpenStreamForReadAsync
na našem StorageFile
, abychom dostali Stream
pro čtení:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var stream = await storageFile.OpenStreamForReadAsync(); |
Nebo volat metodu OpenStreamForWriteAsync
abychom dostali Stream
pro zápis:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var stream = await storageFile.OpenStreamForWriteAsync(); |
Dokonce existují přetížené verze metod, které vrací Stream
pro soubor uvnitř konkrétní složky, pomocí instance StorageFolder
:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var stream = await storageFolder.OpenStreamForReadAsync("myfile.txt"); | |
//or | |
var stream = await storageFolder.OpenStreamForWriteAsync("myfile.txt"); |
Nakonec, pokud chceme jít o úroveň níže, můžeme zavolat metodu CreateSafeFileHandle
, která vrací Microsoft.Win32.SafeHandles.SafeFileHandle
. Ten můžeme použít například s FileStream
API:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var handle = storageFile.CreateSafeFileHandle(options: FileOptions.RandomAccess); | |
var stream = new FileStream(handle, FileAccess.ReadWrite); |