Como: Ler e gravar em um arquivo de dados recém-criadoHow to: Read and write to a newly created data file

As classes System.IO.BinaryWriter e System.IO.BinaryReader são usadas para gravar e ler dados que não sejam cadeias de caracteres.The System.IO.BinaryWriter and System.IO.BinaryReader classes are used for writing and reading data other than character strings. O exemplo a seguir mostra como criar um fluxo de arquivo vazio, gravar dados nele e ler dados dele.The following example shows how to create an empty file stream, write data to it, and read data from it.

O exemplo cria um arquivo de dados chamado Test.data no diretório atual, cria os objetos BinaryWriter e BinaryReader associados e usa o objeto BinaryWriter para gravar os inteiros de 0 a 10 em Test.data, o que deixa o ponteiro de arquivo no final do arquivo.The example creates a data file called Test.data in the current directory, creates the associated BinaryWriter and BinaryReader objects, and uses the BinaryWriter object to write the integers 0 through 10 to Test.data, which leaves the file pointer at the end of the file. Em seguida, o objeto BinaryReader define o ponteiro de arquivo novamente para a origem e lê o conteúdo especificado.The BinaryReader object then sets the file pointer back to the origin and reads out the specified content.

Observação

Se Test.data já existir no diretório atual, uma exceção IOException será gerada.If Test.data already exists in the current directory, an IOException exception is thrown. Use a opção de modo de arquivo FileMode.Create em vez de FileMode.CreateNew para sempre criar um arquivo sem gerar uma exceção.Use the file mode option FileMode.Create rather than FileMode.CreateNew to always create a new file without throwing an exception.

ExemploExample

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.

Consulte tambémSee also