Dela via


Skapa, skriva och läsa en fil

viktiga API:er

Läsa och skriva en fil med hjälp av ett StorageFile-objekt.

Anmärkning

 Ett fullständigt exempel finns i exemplet på filåtkomst.

Förutsättningar

Skapa en fil

Så här skapar du en fil i appens lokala mapp. Om den redan finns ersätter vi den.

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

Skriva till en fil

Så här skriver du till en skrivbar fil på disk med klassen StorageFile . Det vanliga första steget för vart och ett av sätten att skriva till en fil (såvida du inte skriver till filen direkt efter att du har skapat den) är att hämta filen med 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
}

Skriva text till en fil

Skriv text till filen genom att anropa metoden 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");
}

Skriva byte till en fil med hjälp av en buffert (2 steg)

  1. Anropa först CryptographicBuffer.ConvertStringToBinary för att hämta en buffert av byte (baserat på en sträng) som du vill skriva till filen.

    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. Skriv sedan byteen från bufferten till filen genom att anropa metoden FileIO.WriteBufferAsync .

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

Skriva text till en fil med hjälp av en ström (4 steg)

  1. Öppna först filen genom att anropa metoden StorageFile.OpenAsync . Den returnerar en ström av filens innehåll när den öppna åtgärden är klar.

    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. Hämta sedan en utdataström genom att anropa metoden IRandomAccessStream.GetOutputStreamAt från stream. Om du använder C#, omslut detta i en using-sats för att hantera utdataströmmens livslängd. Om du använder C++/WinRT kan du styra dess livslängd genom att omsluta det i ett block eller ställa in det på nullptr när du är klar med det.

    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. Lägg nu till den här koden (om du använder C#, inom den befintliga using-satsen) för att skriva till utflödesströmmen genom att skapa ett nytt DataWriter-objekt och anropa WriteString-metoden.

    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. Slutligen lägger du till den här koden (om du använder C#, inom instruktionen inre användning) för att spara texten i filen med DataWriter.StoreAsync och stänga strömmen med IOutputStream.FlushAsync.

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

Metodtips för att skriva till en fil

Mer information och vägledning om bästa praxis finns i Metodtips för att skriva till filer.

Läsa från en fil

Så här läser du från en fil på disk med klassen StorageFile . Det vanliga första steget för vart och ett av sätten att läsa från en fil är att hämta filen med 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

Läsa text från en fil

Läs text från filen genom att anropa metoden 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);
}

Läsa text från en fil med hjälp av en buffert (2 steg)

  1. Anropa först metoden 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. Använd sedan ett DataReader-objekt för att först läsa längden på bufferten och sedan dess innehåll.

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

Läsa text från en fil med hjälp av en ström (4 steg)

  1. Öppna en dataström för filen genom att anropa metoden StorageFile.OpenAsync . Den returnerar en ström av filens innehåll när åtgärden är klar.

    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. Hämta storleken på strömmen som ska användas senare.

    ulong size = stream.Size;
    
    uint64_t size{ stream.Size() };
    // The code in step 3 goes here.
    
  3. Hämta en indataström genom att anropa metoden IRandomAccessStream.GetInputStreamAt . Placera detta i en using-instruktion för att hantera strömmens livslängd. Ange 0 när du anropar GetInputStreamAt för att ange positionen till början av strömmen.

    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. Slutligen lägger du till den här koden i den befintliga using-instruktionen för att hämta ett DataReader-objekt på strömmen och läser sedan texten genom att anropa DataReader.LoadAsync och 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) };
    

Se även