Cómo: Abrir y anexar a un archivo de registro
Actualización: noviembre 2007
StreamWriter y StreamReader escriben y leen caracteres de secuencias. En el siguiente ejemplo de código, se abre el archivo log.txt para escribir en él, o se crea el archivo si todavía no existe y se agrega información al final del archivo. Seguidamente, se escribe el contenido del archivo en la salida estándar para su presentación. Como alternativa a este ejemplo,la información se podría almacenar como una única cadena o matriz de cadenas, y el método WriteAllText o WriteAllLines se podría emplear para conseguir la misma funcionalidad.
Nota: |
---|
Los usuarios de Visual Basic pueden elegir utilizar los métodos y propiedades proporcionados por los objetos My.Application.Log o My.Computer.FileSystem para crear archivos de registro o escribir en ellos. Para obtener más información, vea My.Application.Log (Objeto) y My.Computer.FileSystem (Objeto). |
Ejemplo
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();
}
}
Vea también
Tareas
Cómo: Crear una lista de directorios
Cómo: Leer y escribir en un archivo de datos recién creado
Cómo: Leer texto de un archivo
Cómo: Escribir texto en un archivo
Cómo: Leer caracteres de una cadena
Cómo: Escribir caracteres en una cadena