次の方法で共有


方法: 新しく作成されたデータ ファイルの読み取りと書き込み

System.IO.BinaryWriterクラスとSystem.IO.BinaryReader クラスは、文字列以外のデータの書き込みと読み取りに使用されます。 次の例は、空のファイル ストリームを作成し、そのストリームにデータを書き込み、そこからデータを読み取る方法を示しています。

この例では、 Test.data というデータ ファイルを現在のディレクトリに作成し、関連付けられた BinaryWriter オブジェクトと BinaryReader オブジェクトを作成し、 BinaryWriter オブジェクトを使用して、整数 0 から 10 を Test.data に書き込みます。これにより、ファイル ポインターはファイルの末尾に残ります。 次に、 BinaryReader オブジェクトは、ファイル ポインターを元の位置に戻し、指定されたコンテンツを読み取ります。

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

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.

こちらも参照ください