Fájl létrehozása, írása és olvasása

Fontos API-k

Fájl olvasása és írása egy StorageFile objektummal.

Megjegyzés:

 A teljes minta a Fájlhozzáférés mintában található.

Előfeltételek

Fájl létrehozása

Az alábbiakban bemutatjuk, hogyan hozhat létre fájlt az alkalmazás helyi mappájában. Ha már létezik, lecseréljük.

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

Írás fájlba

Az alábbiakban bemutatjuk, hogyan írhat írható fájlba a lemezen a StorageFile osztály használatával. A fájlba való írás minden egyes módjának gyakori első lépése (hacsak nem közvetlenül a létrehozása után ír a fájlba) a storageFolder.GetFileAsync fájl lekérése.

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
}

Szöveg írása fájlba

Írjon szöveget a fájlba a FileIO.WriteTextAsync metódus meghívásával.

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

Bájtok írása fájlba puffer használatával (2 lépés)

  1. Először hívja meg a CryptographicBuffer.ConvertStringToBinary függvényt a fájlba írni kívánt bájtok pufferének lekéréséhez (sztring alapján).

    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. Ezután írja be a bájtokat a pufferből a fájlba a FileIO.WriteBufferAsync metódus meghívásával.

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

Szöveg írása fájlba stream használatával (4 lépés)

  1. Először nyissa meg a fájlt a StorageFile.OpenAsync metódus meghívásával. A fájl tartalmának streamjét adja vissza a megnyitási művelet befejeződésekor.

    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. Ezután kérje le a kimeneti streamet az IRandomAccessStream.GetOutputStreamAt metódus meghívásával a stream. Ha C#-ot használ, akkor a kimeneti stream élettartamának kezeléséhez ezt egy használatutasításba kell belefoglalnia. Ha a C++/WinRT-t használja, akkor az élettartamát úgy szabályozhatja, hogy egy blokkba zárja, vagy beállíthatja nullptr-re, amikor végzett vele.

    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. Most adja hozzá ezt a kódot (ha C#-ot használ, a meglévő felhasználói utasításon belül), hogy egy új DataWriter-objektum létrehozásával és a DataWriter.WriteString metódus meghívásával írjon a kimeneti streambe.

    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. Végül adja hozzá ezt a kódot (ha C#-ot használ, a belső felhasználói utasításon belül), hogy mentse a szöveget a fájlba a DataWriter.StoreAsync használatával, és zárja be a streamet az IOutputStream.FlushAsync használatával.

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

Ajánlott eljárások fájlba íráshoz

További részletekért és ajánlott eljárásokkal kapcsolatos útmutatásért tekintse meg a fájlok írásának ajánlott eljárásait.

Olvasás fájlból

Így olvashat egy lemezen lévő fájlból a StorageFile osztály használatával. A fájlok olvasási módjainak gyakori első lépése a fájl lekérése a StorageFolder.GetFileAsync használatával.

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

Szöveg olvasása fájlból

A FileIO.ReadTextAsync metódus meghívásával szöveget olvashat a fájlból.

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

Szöveg olvasása fájlból puffer használatával (2 lépés)

  1. Először hívja meg a FileIO.ReadBufferAsync metódust .

    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. Ezután egy DataReader-objektum használatával olvassa be először a puffer hosszát, majd annak tartalmát.

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

Szöveg olvasása fájlból stream használatával (4 lépés)

  1. Nyisson meg egy streamet a fájlhoz a StorageFile.OpenAsync metódus meghívásával. A művelet befejezésekor visszaadja a fájl tartalmának adatfolyamát.

    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. Kérje le a később használni kívánt stream méretét.

    ulong size = stream.Size;
    
    uint64_t size{ stream.Size() };
    // The code in step 3 goes here.
    
  3. Bemeneti stream lekérése az IRandomAccessStream.GetInputStreamAt metódus meghívásával. A stream élettartamának kezeléséhez tegye ezt egy felhasználói utasításba. Adja meg a 0 értéket, amikor meghívja a GetInputStreamAt parancsot, hogy a pozíciót a stream elejére állítsa.

    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. Végül adja hozzá ezt a kódot a meglévő 'using' nyilatkozatba, hogy létrehozzon egy DataReader objektumot a streamen, majd a szöveget a DataReader.LoadAsync és DataReader.ReadString függvények meghívásával olvassa el.

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

Lásd még