Compartilhar via


Como: em em aberto e anexar em um arquivo de log

StreamWriter e StreamReaderescrevem e gravam caracteres a partir de fluxos de caracteres.O exemplo de código a seguir abre o arquivo log.txt para entrada, ou cria o arquivo se ele ainda não existir e acrescenta informações ao final do arquivo.O conteúdo do arquivo, em seguida, é gravado em uma saída padrão para exibição.Como uma alternativa para esse exemplo, as informações poderiam ser armazenadas como uma única sequência de caracteres ou matriz de sequências e os métodos WriteAllText ou WriteAllLines podem ser usados para alcançar a mesma funcionalidade.

Observação:

Os usuários do Visual Basic podem optar por usar os métodos e propriedades fornecidas pela My.Application.Log ou My.Computer.FileSystem objetos para criar ou gravar em arquivos de log. Para obter mais informações, consulte Objeto My.Application.Log e Objeto My.Computer.FileSystem.

Exemplo

Option Explicit On 
Option Strict On
Imports System
Imports System.IO
Imports Microsoft.VisualBasic
Class DirAppend
    Public Shared Sub Main()
        Using w As StreamWriter = File.AppendText("log.txt")
            Log("Test1", w)
            Log("Test2", w)
            ' Close the writer and underlying file.
            w.Close()
        End Using
        ' Open and read the file.
        Using r As StreamReader = File.OpenText("log.txt")
            DumpLog(r)
        End Using
    End Sub
    Public Shared Sub Log(ByVal logMessage As String, ByVal w As TextWriter)
        w.Write(ControlChars.CrLf & "Log Entry : ")
        w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString())
        w.WriteLine("  :")
        w.WriteLine("  :{0}", logMessage)
        w.WriteLine("-------------------------------")
        ' Update the underlying file.
        w.Flush()
    End Sub
    Public Shared Sub DumpLog(ByVal r As StreamReader)
        ' While not at the end of the file, read and write lines.
        Dim line As String
        line = r.ReadLine()
        While Not line Is Nothing
            Console.WriteLine(line)
            line = r.ReadLine()
        End While
        r.Close()
    End Sub
End Class
using System;
using System.IO;
class DirAppend
{
    public static void Main(String[] args)
    {
        using (StreamWriter w = File.AppendText("log.txt"))
        {
            Log ("Test1", w);
            Log ("Test2", w);
            // Close the writer and underlying file.
            w.Close();
        }
        // Open and read the file.
        using (StreamReader r = File.OpenText("log.txt"))
        {
            DumpLog (r);
        }
    }
    public static void Log (String logMessage, TextWriter w)
    {
        w.Write("\r\nLog Entry : ");
        w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
            DateTime.Now.ToLongDateString());
        w.WriteLine("  :");
        w.WriteLine("  :{0}", logMessage);
        w.WriteLine ("-------------------------------");
        // Update the underlying file.
        w.Flush(); 
    }
    public static void DumpLog (StreamReader r)
    {
        // While not at the end of the file, read and write lines.
        String line;
        while ((line=r.ReadLine())!=null)
        {
            Console.WriteLine(line);
        }
        r.Close();
    }
}

Consulte também

Tarefas

Como: Criar uma listagem de diretório

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

Como: Ler texto de um arquivo

Como: Gravar um arquivo de texto

Como: Caracteres de leitura de uma seqüência de caracteres

Como: Escrever caracteres para uma string

Conceitos

Arquivo básico de E/S

Referência

StreamWriter

StreamReader

File.AppendText

File.OpenText

StreamReader.ReadLine