Partilhar via


Criar, escrever e ler um ficheiro

APIs importantes

Leia e escreva um ficheiro usando um objeto StorageFile.

Observação

 Para um exemplo completo, consulte o exemplo de acesso ao ficheiro.

Pré-requisitos

Criação de um ficheiro

Aqui está como criar um ficheiro na pasta local da aplicação. Se já existe, substituímos.

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

Escrita num ficheiro

Aqui está como escrever num ficheiro gravável num disco usando a classe StorageFile . O primeiro passo comum para cada uma das formas de escrever num ficheiro (a menos que esteja a escrever imediatamente após o criar) é obter o ficheiro com o 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
}

Escrever texto num ficheiro

Escreva texto no seu ficheiro chamando o método 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");
}

Escrever bytes num ficheiro usando um buffer (2 passos)

  1. Primeiro, chama CryptographicBuffer.ConvertStringToBinary para obter um buffer dos bytes (baseados numa cadeia de caracteres) que quer escrever no seu ficheiro.

    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.
    }
    
  2. Depois escreve os bytes do teu buffer no teu ficheiro chamando o método FileIO.WriteBufferAsync .

    await Windows.Storage.FileIO.WriteBufferAsync(sampleFile, buffer);
    
    co_await Windows::Storage::FileIO::WriteBufferAsync(sampleFile, buffer);
    

Escrever texto num ficheiro usando um fluxo (4 passos)

  1. Primeiro, abra o ficheiro chamando o método StorageFile.OpenAsync . Devolve um fluxo do conteúdo do ficheiro quando a operação de abertura termina.

    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.
    }
    
  2. De seguida, obtenha um fluxo de saída chamando o método IRandomAccessStream.GetOutputStreamAt a partir do stream. Se estiveres a usar C#, então inclui isto numa instrução using para gerir a vida útil do fluxo de saída. Se estiveres a usar C++/WinRT, podes controlar a sua vida útil encerrando-a num bloco, ou definindo-a para nullptr quando terminares.

    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.
    
  3. Agora adiciona este código (se estiveres a usar C#, dentro da instrução using existente) para escrever no fluxo de saída, criando um novo objeto DataWriter e chamando o método 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.
    
  4. Por fim, adiciona este código (se estiveres a usar C#, dentro da instrução using interna) para guardar o texto no teu ficheiro com DataWriter.StoreAsync e fecha o fluxo com IOutputStream.FlushAsync.

    await dataWriter.StoreAsync();
    await outputStream.FlushAsync();
    
    dataWriter.StoreAsync();
    outputStream.FlushAsync();
    

Boas práticas para escrever para um ficheiro

Para mais detalhes e orientações de boas práticas, consulte Melhores práticas para escrita em ficheiros.

Leitura de um ficheiro

Aqui está como ler a partir de um ficheiro em disco usando a classe StorageFile . O primeiro passo comum para cada uma das formas de ler a partir de um ficheiro é obter o ficheiro com 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

Ler texto de um ficheiro

Leia o texto do seu ficheiro chamando o método 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);
}

Ler texto de um ficheiro usando um buffer (2 passos)

  1. Primeiro, chame o método 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.
    
  2. Depois, use um objeto DataReader para ler primeiro o comprimento do buffer e depois o seu conteúdo.

    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()) };
    

Ler texto de um ficheiro usando um fluxo (4 passos)

  1. Abra um fluxo para o seu ficheiro chamando o método StorageFile.OpenAsync . Devolve um fluxo do conteúdo do ficheiro quando a operação termina.

    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.
    
  2. Obtenha o tamanho do fluxo para usar mais tarde.

    ulong size = stream.Size;
    
    uint64_t size{ stream.Size() };
    // The code in step 3 goes here.
    
  3. Obtenha um fluxo de entrada chamando o método IRandomAccessStream.GetInputStreamAt . Coloca isto numa instrução using para gerir o tempo de vida do fluxo. Especifique 0 quando chamar GetInputStreamAt para definir a posição para o início do fluxo.

    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.
    
  4. Por fim, adicione este código dentro da instrução using existente para obter um objeto DataReader no fluxo e depois leia o texto chamando 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) };
    

Consulte também