次の方法で共有


Windows App SDK と .NET を使用してファイルとフォルダーにアクセスする

パッケージ化された Windows App SDK アプリでは、.NET API を利用して、ファイルの読み取りと書き込み、フォルダーの操作、ドライブやボリューム情報の読み取りを行うことができます。 また、パッケージ化されたデスクトップ アプリでは、Windows SDK の WinRT API と Win32 API の両方と、.NET SDK で提供される API を利用できます。 この記事では、.NET System.IO API を使用して、ファイルの読み取りと書き込み、ドライブとフォルダーの管理、およびメモリ ストリームを使用して文字列データをエンコードまたはデコードする方法に関するガイダンスを示します。

.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 でドライブとフォルダーを管理する

次の例では、DirectoryInfo クラスと Directory クラスを使用して、フォルダーの作成、削除、管理を行う方法を示します。 この例では、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);
}

Note

.NET ストリームと WinRT ストリーム間の変換に関する情報については、「方法: .NET ストリームと Windows ランタイム ストリームの間で変換を行う」を参照してください。

関連項目

Windows App SDK と WinRT API を使用してファイルとフォルダーにアクセスする

Windows App SDK を含むファイル、フォルダー、およびライブラリ