共用方式為


使用 Windows App SDK 和 .NET 存取檔案和資料夾

本文說明如何在封裝的 WinUI 應用程式中使用 .NET API 存取檔案和資料夾。 您將學習讀取和寫入檔案、管理目錄和磁碟機,以及使用記憶體流進行字串編碼和解碼。

WinUI 應用程式可以將 .NET API 與 WinRT 和 Win32 API 搭配使用,以提供完整的檔案系統存取。 本文中的範例著重於 System.IO 命名空間,它為檔案和目錄作業提供核心功能。

先決條件

  • 已安裝 WinUI 應用程式開發 工作負載的 Visual Studio 2022
  • 已封裝的 WinUI 專案
  • 基本熟悉 C# 和 .NET 開發

您將學到什麼

在本文中,您將學會如何:

使用 .NET API 讀取和寫入檔案

在下列範例中, ReadWriteFiles 建立新的檔案、將一組整數寫入檔案,然後從檔案中讀取整數。 此範例會使用 FileStream 類別來建立新的檔案,並開啟檔案以供讀取或寫入。 此範例會使用 BinaryWriter 類別將整數寫入檔案, 而 BinaryReader 類別則會從檔案讀取整數。

using System.IO;
...
ReadWriteFiles("test.bin");
...
private void ReadWriteFiles(string fileName)
{
    if (File.Exists(fileName))
    {
        Console.WriteLine($"{fileName} already exists!");
        return;
    }

    using (FileStream fs = new(fileName, FileMode.CreateNew))
    {
        using BinaryWriter writer = new(fs);
        for (int i = 0; i < 11; i++)
        {
            writer.Write(i);
        }
    }

    using (FileStream fs = new(fileName, FileMode.Open, FileAccess.Read))
    {
        using BinaryReader reader = new(fs);
        for (int i = 0; i < 11; i++)
        {
            Console.WriteLine(reader.ReadInt32());
        }
    }
}

管理 .NET 中的磁碟驅動器和資料夾

下列範例示範如何使用 DirectoryInfoDirectory 類別來建立、刪除和管理資料夾。 此範例會使用 DirectoryInfo 類別來建立新的目錄、建立子目錄,以及刪除目錄。 類別 DirectoryInfo 提供透過目錄和子目錄建立、移動和列舉的方法。 類別 Directory 提供 靜態 方法來建立、移動及列舉目錄和子目錄。

using System.IO;
...
private void FolderTest()
{
    FolderManagement(@"c:\MyDir", "Projects");
}
private void FolderManagement(string path, string subfolderName)
{
    DirectoryInfo di = new(path);
    try
    {
        // Create directory if it doesn't exist
        if (di.Exists)
        {
            Console.WriteLine("Path already exists.");
        }
        else
        {
            di.Create();
            Console.WriteLine("The directory was created successfully.");
        }

        // Create subdirectory if it doesn't exist
        string subfolderPath = Path.Combine(path, subfolderName);
        if (Directory.Exists(subfolderPath))
        {
            Console.WriteLine("Subfolder path already exists.");
        }
        else
        {
            di.CreateSubdirectory(subfolderName);
            Console.WriteLine("The subdirectory was created successfully.");
        }

        // Delete directory
        di.Delete(true);
        Console.WriteLine("The directory was deleted successfully.");
    }
    catch (Exception ex)
    {
        Console.WriteLine("The process failed: {0}", ex.ToString());
    }
}

這個範例使用靜態 GetDrives 方法來擷取系統上所有磁碟驅動器的相關信息。 DriveInfo 類別提供磁碟驅動器的相關信息,例如磁碟驅動器類型、標籤、檔案系統和可用空間。

using System.IO;
...
private void DriveManagement()
{
    DriveInfo[] drives = DriveInfo.GetDrives();

    foreach (DriveInfo d in drives)
    {
        Console.WriteLine($"Drive name: {d.Name}");
        Console.WriteLine($"  Drive type: {d.DriveType}");
        if (d.IsReady)
        {
            Console.WriteLine($"  Volume label: {d.VolumeLabel}");
            Console.WriteLine($"  File system type: {d.DriveFormat}");
            Console.WriteLine($"  Space available to user: {d.AvailableFreeSpace, 15} bytes");
            Console.WriteLine($"  Total available space: {d.TotalFreeSpace, 15} bytes");
            Console.WriteLine($"  Total size of drive: {d.TotalSize, 15} bytes ");
        }
    }
}

使用 MemoryStream 編碼和譯碼字串

此範例示範如何使用 MemoryStream 類別來編碼和譯碼字串數據。 它會先建立 MemoryStream ,以異步方式將字串寫入記憶體數據流,然後從記憶體數據流讀取字串。 Encoding 類別可用來將字串轉換成位元組陣列,然後將位元組數位列寫入記憶體數據流。 接著,StreamReader 會用來從記憶體數據流異步讀取位元組陣列,然後藉由呼叫 ReadToEndAsync 將位元組數位轉換為字元串。

using System.IO;
using System.Text;
...
private async Task EncodeDecodeStringAsync(string inputData)
{
    using MemoryStream stream = new();
    var inputBytes = Encoding.UTF8.GetBytes(inputData);
    await stream.WriteAsync(inputBytes, 0, inputBytes.Length);
    stream.Seek(0, SeekOrigin.Begin);

    using StreamReader reader = new(stream);
    string text = await reader.ReadToEndAsync();
    Console.WriteLine(text);
}

備註

如需在 .NET 數據流和 WinRT 數據流之間轉換的相關信息,請參閱 如何:在 .NET 和 Windows 運行時間數據流之間轉換

另請參閱

使用 Windows App SDK 和 WinRT API 存取檔案和資料夾

使用 Windows App SDK 的檔案、資料夾和程式庫