Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
API Importanti
Leggere e scrivere un file usando un oggetto StorageFile.
Annotazioni
Per un esempio completo, vedere l'esempio di accesso ai file.
Prerequisiti
Informazioni sulla programmazione asincrona per le app WinUI
Per informazioni su come scrivere app asincrone in C#, vedere Chiamare API asincrone in C# o Visual Basic. Per informazioni su come scrivere app asincrone in C++/WinRT, vedere Concorrenza e operazioni asincrone con C++/WinRT.
Sapere come ottenere il file da cui si vuole leggere, scrivere o entrambi
Per sapere come ottenere un file, utilizzare un selettore di file in Apri file e cartelle con un selettore.
Creazione di un file
Ecco come creare un file nella cartella locale dell'app. Se esiste già, lo sostituiamo.
// Create sample file; replace if exists.
Windows.Storage.StorageFolder storageFolder =
Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile sampleFile =
await storageFolder.CreateFileAsync("sample.txt",
Windows.Storage.CreationCollisionOption.ReplaceExisting);
// MainPage.h
#include <winrt/Windows.Storage.h>
...
Windows::Foundation::IAsyncAction ExampleCoroutineAsync()
{
// Create a sample file; replace if exists.
Windows::Storage::StorageFolder storageFolder{ Windows::Storage::ApplicationData::Current().LocalFolder() };
co_await storageFolder.CreateFileAsync(L"sample.txt", Windows::Storage::CreationCollisionOption::ReplaceExisting);
}
Scrittura in un file
Ecco come scrivere in un file scrivibile su disco usando la classe StorageFile . Il primo passaggio comune per ognuno dei modi di scrivere in un file (a meno che non si stia scrivendo nel file immediatamente dopo averlo creato) consiste nel ottenere il file con StorageFolder.GetFileAsync.
Windows.Storage.StorageFolder storageFolder =
Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile sampleFile =
await storageFolder.GetFileAsync("sample.txt");
// MainPage.h
#include <winrt/Windows.Storage.h>
...
Windows::Foundation::IAsyncAction ExampleCoroutineAsync()
{
Windows::Storage::StorageFolder storageFolder{ Windows::Storage::ApplicationData::Current().LocalFolder() };
auto sampleFile{ co_await storageFolder.CreateFileAsync(L"sample.txt", Windows::Storage::CreationCollisionOption::ReplaceExisting) };
// Process sampleFile
}
Scrittura di testo in un file
Scrivere testo nel file chiamando il metodo FileIO.WriteTextAsync .
await Windows.Storage.FileIO.WriteTextAsync(sampleFile, "Swift as a shadow");
// MainPage.h
#include <winrt/Windows.Storage.h>
...
Windows::Foundation::IAsyncAction ExampleCoroutineAsync()
{
Windows::Storage::StorageFolder storageFolder{ Windows::Storage::ApplicationData::Current().LocalFolder() };
auto sampleFile{ co_await storageFolder.GetFileAsync(L"sample.txt") };
// Write text to the file.
co_await Windows::Storage::FileIO::WriteTextAsync(sampleFile, L"Swift as a shadow");
}
Scrittura di byte in un file tramite un buffer (2 passaggi)
Prima di tutto, chiama CryptographicBuffer.ConvertStringToBinary per ottenere un buffer dei byte (in base a una stringa) che vuoi scrivere nel file.
var buffer = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary( "What fools these mortals be", Windows.Security.Cryptography.BinaryStringEncoding.Utf8);// MainPage.h #include <winrt/Windows.Security.Cryptography.h> #include <winrt/Windows.Storage.h> #include <winrt/Windows.Storage.Streams.h> ... Windows::Foundation::IAsyncAction ExampleCoroutineAsync() { Windows::Storage::StorageFolder storageFolder{ Windows::Storage::ApplicationData::Current().LocalFolder() }; auto sampleFile{ co_await storageFolder.GetFileAsync(L"sample.txt") }; // Create the buffer. Windows::Storage::Streams::IBuffer buffer{ Windows::Security::Cryptography::CryptographicBuffer::ConvertStringToBinary( L"What fools these mortals be", Windows::Security::Cryptography::BinaryStringEncoding::Utf8)}; // The code in step 2 goes here. }Scrivere quindi i byte dal buffer al file chiamando il metodo FileIO.WriteBufferAsync .
await Windows.Storage.FileIO.WriteBufferAsync(sampleFile, buffer);co_await Windows::Storage::FileIO::WriteBufferAsync(sampleFile, buffer);
Scrittura di testo in un file usando un flusso (4 passaggi)
Aprire prima di tutto il file chiamando il metodo StorageFile.OpenAsync . Restituisce un flusso del contenuto del file al termine dell'operazione di apertura.
var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);// MainPage.h #include <winrt/Windows.Storage.h> #include <winrt/Windows.Storage.Streams.h> ... Windows::Foundation::IAsyncAction ExampleCoroutineAsync() { Windows::Storage::StorageFolder storageFolder{ Windows::Storage::ApplicationData::Current().LocalFolder() }; auto sampleFile{ co_await storageFolder.GetFileAsync(L"sample.txt") }; Windows::Storage::Streams::IRandomAccessStream stream{ co_await sampleFile.OpenAsync(Windows::Storage::FileAccessMode::ReadWrite) }; // The code in step 2 goes here. }Ottenere quindi un flusso di output chiamando il metodo IRandomAccessStream.GetOutputStreamAt da
stream. Se si usa C#, racchiuderlo in un'istruzione using per gestire la durata del flusso di output. Se usi C++/WinRT, puoi controllarne la durata racchiudendolo in un blocco o impostandolo sunullptral termine dell'operazione.using (var outputStream = stream.GetOutputStreamAt(0)) { // We'll add more code here in the next step. } stream.Dispose(); // Or use the stream variable (see previous code snippet) with a using statement as well.Windows::Storage::Streams::IOutputStream outputStream{ stream.GetOutputStreamAt(0) }; // The code in step 3 goes here.Aggiungere ora questo codice (se si usa C#, all'interno dell'istruzione using esistente) per scrivere nel flusso di output creando un nuovo oggetto DataWriter e chiamando il metodo DataWriter.WriteString .
using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream)) { dataWriter.WriteString("DataWriter has methods to write to various types, such as DataTimeOffset."); }Windows::Storage::Streams::DataWriter dataWriter; dataWriter.WriteString(L"DataWriter has methods to write to various types, such as DataTimeOffset."); // The code in step 4 goes here.Infine, aggiungere questo codice (se si usa C#, all'interno dell'istruzione using interna) per salvare il testo nel file con DataWriter.StoreAsync e chiudere il flusso con IOutputStream.FlushAsync.
await dataWriter.StoreAsync(); await outputStream.FlushAsync();dataWriter.StoreAsync(); outputStream.FlushAsync();
Procedure consigliate per la scrittura in un file
Per altri dettagli e indicazioni sulle procedure consigliate, vedere Procedure consigliate per la scrittura in file.
Lettura da un file
Ecco come leggere da un file su disco usando la classe StorageFile . Il primo passaggio comune per ogni modalità di lettura da un file consiste nel ottenere il file con StorageFolder.GetFileAsync.
Windows.Storage.StorageFolder storageFolder =
Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile sampleFile =
await storageFolder.GetFileAsync("sample.txt");
Windows::Storage::StorageFolder storageFolder{ Windows::Storage::ApplicationData::Current().LocalFolder() };
auto sampleFile{ co_await storageFolder.GetFileAsync(L"sample.txt") };
// Process file
Lettura di testo da un file
Leggere il testo dal file chiamando il metodo FileIO.ReadTextAsync .
string text = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);
Windows::Foundation::IAsyncOperation<winrt::hstring> ExampleCoroutineAsync()
{
Windows::Storage::StorageFolder storageFolder{ Windows::Storage::ApplicationData::Current().LocalFolder() };
auto sampleFile{ co_await storageFolder.GetFileAsync(L"sample.txt") };
co_return co_await Windows::Storage::FileIO::ReadTextAsync(sampleFile);
}
Lettura del testo da un file tramite un buffer (2 passaggi)
Prima di tutto, chiamare il metodo FileIO.ReadBufferAsync .
var buffer = await Windows.Storage.FileIO.ReadBufferAsync(sampleFile);Windows::Storage::StorageFolder storageFolder{ Windows::Storage::ApplicationData::Current().LocalFolder() }; auto sampleFile{ co_await storageFolder.GetFileAsync(L"sample.txt") }; Windows::Storage::Streams::IBuffer buffer{ co_await Windows::Storage::FileIO::ReadBufferAsync(sampleFile) }; // The code in step 2 goes here.Usare quindi un oggetto DataReader per leggere prima la lunghezza del buffer e quindi il relativo contenuto.
using (var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer)) { string text = dataReader.ReadString(buffer.Length); }auto dataReader{ Windows::Storage::Streams::DataReader::FromBuffer(buffer) }; winrt::hstring bufferText{ dataReader.ReadString(buffer.Length()) };
Lettura di testo da un file tramite un flusso (4 passaggi)
Apri un flusso per il tuo file chiamando il metodo StorageFile.OpenAsync. Restituisce un flusso del contenuto del file al termine dell'operazione.
var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.Read);Windows::Storage::StorageFolder storageFolder{ Windows::Storage::ApplicationData::Current().LocalFolder() }; auto sampleFile{ co_await storageFolder.GetFileAsync(L"sample.txt") }; Windows::Storage::Streams::IRandomAccessStream stream{ co_await sampleFile.OpenAsync(Windows::Storage::FileAccessMode::Read) }; // The code in step 2 goes here.Ottieni la dimensione del flusso da usare in un secondo momento.
ulong size = stream.Size;uint64_t size{ stream.Size() }; // The code in step 3 goes here.Ottenere un flusso di input chiamando il metodo IRandomAccessStream.GetInputStreamAt . Inserire questo valore in un'istruzione using per gestire la durata del flusso. Specificare 0 quando si chiama GetInputStreamAt per impostare la posizione all'inizio del flusso.
using (var inputStream = stream.GetInputStreamAt(0)) { // We'll add more code here in the next step. }Windows::Storage::Streams::IInputStream inputStream{ stream.GetInputStreamAt(0) }; Windows::Storage::Streams::DataReader dataReader{ inputStream }; // The code in step 4 goes here.Infine, aggiungere questo codice all'interno dell'istruzione using esistente per ottenere un oggetto DataReader nel flusso e quindi leggere il testo chiamando DataReader.LoadAsync e DataReader.ReadString.
using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); string text = dataReader.ReadString(numBytesLoaded); }unsigned int cBytesLoaded{ co_await dataReader.LoadAsync(size) }; winrt::hstring streamText{ dataReader.ReadString(cBytesLoaded) };