Создание, запись и чтение файла

Основные API

Чтение и запись файла с помощью объекта StorageFile .

Замечание

 Полный пример см. в примере доступа к файлам.

Необходимые условия

Создание файла

Вот как создать файл в локальной папке приложения. Если он уже существует, мы заменяем его.

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

Запись в файл

Так можно записать данные в файл на диске, который поддерживает запись, с использованием класса StorageFile. Распространенный первый шаг для каждого из способов записи в файл (если вы не записываете в файл сразу после его создания) заключается в получении файла с использованием 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
}

Запись текста в файл

Напишите текст в файл, вызвав метод 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");
}

Запись байтов в файл с помощью буфера (2 шага)

  1. Сначала вызовите CryptographicBuffer.ConvertStringToBinary , чтобы получить буфер байтов (на основе строки), который требуется записать в файл.

    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. Затем запишите байты из буфера в файл, вызвав метод FileIO.WriteBufferAsync .

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

Запись текста в файл с помощью потока (4 шага)

  1. Сначала откройте файл, вызвав метод StorageFile.OpenAsync . Он возвращает поток содержимого файла после завершения операции открытия.

    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. Затем получите выходной поток, вызвав метод IRandomAccessStream.GetOutputStreamAt из stream. Если вы используете C#, заключите его в инструкцию using для управления временем существования выходного потока. Если вы используете C++/WinRT, вы можете управлять его сроком службы, заключив его в блок или задав его в nullptr, когда закончите с ним.

    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. Теперь добавьте этот код (если вы используете C#, в существующей инструкции using) для записи в выходной поток путем создания объекта DataWriter и вызова метода 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. Наконец, добавьте этот код (если вы используете C#, внутри вложенной инструкции using), чтобы сохранить текст в файл с помощью DataWriter.StoreAsync и закрыть поток с IOutputStream.FlushAsync.

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

Рекомендации по записи в файл

Для получения более подробных сведений и рекомендаций, см. раздел "Лучшие практики записи в файлы".

Чтение из файла

Ниже показано, как считывать из файла на диске с помощью класса StorageFile . Первым шагом каждого из способов чтения из файла является получение файла, используя 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

Чтение текста из файла

Чтение текста из файла путем вызова метода 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);
}

Чтение текста из файла с помощью буфера (2 шага)

  1. Сначала вызовите метод 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. Затем используйте объект DataReader для чтения сначала длины буфера, а затем его содержимого.

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

Чтение текста из файла с помощью потока (4 шага)

  1. Откройте поток для файла, вызвав метод StorageFile.OpenAsync . Он возвращает поток содержимого файла после завершения операции.

    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. Получите размер потока, который будет использоваться позже.

    ulong size = stream.Size;
    
    uint64_t size{ stream.Size() };
    // The code in step 3 goes here.
    
  3. Получите входной поток, вызвав метод IRandomAccessStream.GetInputStreamAt . Поместите его в инструкцию using для управления временем существования потока. Укажите значение 0 при вызове GetInputStreamAt, чтобы задать положение в начале потока.

    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. Наконец, добавьте этот код в существующую инструкцию using, чтобы получить объект DataReader в потоке, а затем прочитать текст путем вызова DataReader.LoadAsync и 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) };
    

См. также