共用方式為


建立、寫入和讀取檔案

重要的應用程式介面

使用 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 方法以取得輸出串流。 如果你用的是 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. 最後,在 using 內的 using 語句中加入這段程式碼(如果你用的是 C#),用 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);
}

利用緩衝區從檔案讀取文字(兩步驟)

  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 語句中,以管理串流的生命週期。 當你呼叫 GetInputStreamAt 時,請指定 0,將位置設定為串流的起始。

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

另請參閱