方法: 新しく作成されたデータ ファイルに対して読み書きする

System.IO.BinaryWriter クラスおよび System.IO.BinaryReader クラスは、文字列ではない形式でデータを書き込んだり読み取ったりするために使用します。 次の例では、空のファイル ストリームを作成し、それにデータを書き込み、それからデータを読み取る方法を示します。

この例では、現在のディレクトリに Test.data という名前のデータ ファイルが作成され、関連する BinaryWriter オブジェクトと BinaryReader オブジェクトが作成され、BinaryWriter オブジェクトを使用し、0 から 10 までの整数が Test.data に書き込まれます。ファイル ポインターがファイルの末尾に残ります。 次に、BinaryReader オブジェクトによってファイル ポインターが起点に戻され、指定された内容が読み出されます。

注意

Test.data が既に現在のディレクトリに存在する場合は、IOException 例外がスローされます。 例外をスローせず、常に新しいファイルを作成するには、ファイル モード オプションとして FileMode.CreateNew ではなく FileMode.Create を使用します。

using System;
using System.IO;

class MyStream
{
    private const string FILE_NAME = "Test.data";

    public static void Main()
    {
        if (File.Exists(FILE_NAME))
        {
            Console.WriteLine($"{FILE_NAME} already exists!");
            return;
        }

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

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


// The example creates a file named "Test.data" and writes the integers 0 through 10 to it in binary format.
// It then writes the contents of Test.data to the console with each integer on a separate line.
Imports System.IO

Class MyStream
    Private Const FILE_NAME As String = "Test.data"

    Public Shared Sub Main()
        If File.Exists(FILE_NAME) Then
            Console.WriteLine($"{FILE_NAME} already exists!")
            Return
        End If

        Using fs As New FileStream(FILE_NAME, FileMode.CreateNew)
            Using w As New BinaryWriter(fs)
                For i As Integer = 0 To 10
                    w.Write(i)
                Next
            End Using
        End Using

        Using fs As New FileStream(FILE_NAME, FileMode.Open, FileAccess.Read)
            Using r As New BinaryReader(fs)
                For i As Integer = 0 To 10
                    Console.WriteLine(r.ReadInt32())
                Next
            End Using
        End Using
    End Sub
End Class

' The example creates a file named "Test.data" and writes the integers 0 through 10 to it in binary format.
' It then writes the contents of Test.data to the console with each integer on a separate line.

関連項目