Como: Ler e gravar em um arquivo de dados recém-criado

Aa classes BinaryWriter e BinaryReader são usadas para gravar e ler dados, em vez de sequências de caracteres. O exemplo de código a seguir demonstra a gravação e leitura de dados a partir de um fluxo novo e vazio (Test.data). Após a criação do arquivo de dados no diretório atual, o BinaryWriter e o BinaryReader associados são criados, e o BinaryWriter é usado para gravar os inteiros 0 a 10 para Test.data, que deixa o ponteiro do arquivo no final do arquivo. Depois de definir o ponteiro do arquivo de volta para a origem, o BinaryReader lê o conteúdo especificado.

Exemplo

Imports System
Imports System.IO

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

    Public Shared Sub Main()
        ' Create the new, empty data file.
        If File.Exists(FILE_NAME) Then
            Console.WriteLine("{0} already exists!", FILE_NAME)
            Return
        End If
        Using fs As New FileStream(FILE_NAME, FileMode.CreateNew)
            ' Create the writer for data.
            Using w As New BinaryWriter(fs)
                ' Write data to Test.data.
                For i As Integer = 0 To 10
                    w.Write(i)
                Next
            End Using
        End Using
        ' Create the reader for data.
        Using fs As New FileStream(FILE_NAME, FileMode.Open, FileAccess.Read)
            Using r As New BinaryReader(fs)
                ' Read data from Test.data.
                For i As Integer = 0 To 10
                    Console.WriteLine(r.ReadInt32())
                Next
            End Using
        End Using
    End Sub
End Class
using System;
using System.IO;

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

    public static void Main()
    {
        // Create the new, empty data file.
        if (File.Exists(FILE_NAME))
        {
            Console.WriteLine("{0} already exists!", FILE_NAME);
            return;
        }
        using (FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew))
        {
            // Create the writer for data.
            using (BinaryWriter w = new BinaryWriter(fs))
            {
                // Write data to Test.data.
                for (int i = 0; i < 11; i++)
                {
                    w.Write(i);
                }
            }
        }
        // Create the reader for data.
        using (FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read))
        {
            using (BinaryReader r = new BinaryReader(fs))
            {
                // Read data from Test.data.
                for (int i = 0; i < 11; i++)
                {
                    Console.WriteLine(r.ReadInt32());
                }
            }
        }
    }
}
using namespace System;
using namespace System::IO;

ref class MyStream
{
private:
    static String^ FILE_NAME = "Test.data";

public:
    static void Main()
    {
        // Create the new, empty data file.
        if (File::Exists(FILE_NAME))
        {
            Console::WriteLine("{0} already exists!", FILE_NAME);
            return;
        }
        FileStream^ fs = gcnew FileStream(FILE_NAME, FileMode::CreateNew);
        // Create the writer for data.
        BinaryWriter^ w = gcnew BinaryWriter(fs);
        // Write data to Test.data.
        for (int i = 0; i < 11; i++)
        {
            w->Write(i);
        }
        w->Close();
        fs->Close();
        // Create the reader for data.
        fs = gcnew FileStream(FILE_NAME, FileMode::Open, FileAccess::Read);
        BinaryReader^ r = gcnew BinaryReader(fs);
        // Read data from Test.data.
        for (int i = 0; i < 11; i++)
        {
            Console::WriteLine(r->ReadInt32());
        }
        fs->Close();
    }
};

int main()
{
    MyStream::Main();
}

Programação robusta

Se Test.data já existir no diretório atual, um IOException é apresentada. Use FileMode.Create para sempre criar um novo arquivo sem lançar um IOException.

Consulte também

Tarefas

Como: Criar uma listagem de diretório

Como: Abrir e anexar um arquivo de Log

Como: Ler texto de um arquivo.

Como: Gravar texto em um arquivo

Como: Caracteres de leitura de uma seqüência

Como: Gravar uma seqüência de caracteres

Referência

BinaryReader

BinaryWriter

FileStream

FileStream.Seek

SeekOrigin

Conceitos

Arquivo básico de E/S