Jazyk

Vytvoření, zápis a čtení souboru

důležitá rozhraní API

Čtení a zápis souboru pomocí objektu StorageFile .

Poznámka:

 Kompletní ukázku najdete v ukázce přístupu k souboru.

Předpoklady

Vytvoření souboru

Tady je postup, jak vytvořit soubor v místní složce aplikace. Pokud už existuje, nahradíme ho.

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

Zápis do souboru

Tady je postup zápisu do zapisovatelného souboru na disku pomocí třídy StorageFile . Běžným prvním krokem pro každý ze způsobů zápisu do souboru (pokud do souboru nezapisujete hned po jeho vytvoření) je získání souboru pomocí 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
}

Zápis textu do souboru

Zápis textu do souboru voláním FileIO.WriteTextAsync metoda.

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

Zápis bajtů do souboru pomocí vyrovnávací paměti (2 kroky)

  1. Nejprve zavolejte CryptographicBuffer.ConvertStringToBinary k získání vyrovnávací paměti bajtů (na základě řetězce), které chcete zapisovat do souboru.

    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. Pak zapište bajty z vašeho bufferu do souboru zavoláním metody FileIO.WriteBufferAsync.

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

Zápis textu do souboru pomocí streamu (4 kroky)

  1. Nejprve otevřete soubor voláním metody StorageFile.OpenAsync . Po dokončení operace otevření vrátí datový proud obsahu souboru.

    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. Dále získejte výstupní datový proud voláním metody IRandomAccessStream.GetOutputStreamAt od . Pokud používáte jazyk C#, uzavřete ho do příkazu using pro správu životnosti výstupního datového proudu. Pokud používáte C++/WinRT, můžete jeho životnost řídit tak, že ho uzavřete do bloku nebo nastavíte na nullptr, když s ním skončíte.

    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. Nyní přidejte tento kód (pokud používáte jazyk C# v rámci existujícího příkazu using) k zápisu do výstupního datového proudu vytvořením nového objektu DataWriter a voláním Metody 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{ outputStream };
    dataWriter.WriteString(L"DataWriter has methods to write to various types, such as DataTimeOffset.");
    // The code in step 4 goes here.
    
  4. Nakonec přidejte tento kód (pokud používáte C#, v rámci vnitřního příkazu using) uložte text do souboru pomocí DataWriter.StoreAsync a zavřete datový proud pomocí IOutputStream.FlushAsync.

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

Osvědčené postupy pro zápis do souboru

Další podrobnosti a pokyny k osvědčeným postupům najdete v tématu Osvědčené postupy pro zápis do souborů.

Čtení ze souboru

Tady je postup, jak číst ze souboru na disku pomocí třídy StorageFile . Běžným prvním krokem pro každý ze způsobů čtení ze souboru je získání souboru pomocí 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

Čtení textu ze souboru

Čtěte text ze souboru voláním metody 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);
}

Čtení textu ze souboru pomocí vyrovnávací paměti (2 kroky)

  1. Nejprve zavolejte FileIO.ReadBufferAsync metoda.

    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. Nejprve pomocí objektu DataReader přečtěte délku vyrovnávací paměti a pak její obsah.

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

Čtení textu ze souboru pomocí streamu (4 kroky)

  1. Otevřete stream souboru voláním metody StorageFile.OpenAsync . Po dokončení operace vrátí datový proud obsahu souboru.

    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. Získejte velikost datového proudu, který chcete použít později.

    ulong size = stream.Size;
    
    uint64_t size{ stream.Size() };
    // The code in step 3 goes here.
    
  3. Získejte vstupní datový proud voláním metody IRandomAccessStream.GetInputStreamAt. Vložte ho do příkazu using pro správu životnosti datového proudu. Zadejte 0, abyste při volání GetInputStreamAt nastavili pozici na začátek datového proudu.

    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. Nakonec přidejte tento kód do existujícího příkazu using k získání objektu DataReader ve streamu a pak čtení textu voláním DataReader.LoadAsync a 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) };
    

Viz také