Apertura e aggiunta a un file di log
StreamWriter e StreamReader scrivono e leggono caratteri dai flussi. Nell'esempio di codice che segue viene aperto il file log.txt
e vi vengono accodate informazioni. Nel caso non sia disponibile, il file verrà creato. Il contenuto del file viene quindi scritto nell'output standard, che ne consente la visualizzazione.
Option Explicit On
Option Strict On
Imports System
Imports System.IO
Imports Microsoft.VisualBasic
Class DirAppend
Public Shared Sub Main()
Dim w As StreamWriter = File.AppendText("log.txt")
Log("Test1", w)
Log("Test2", w)
' Close the writer and underlying file.
w.Close()
' Open and read the file.
Dim r As StreamReader = File.OpenText("log.txt")
DumpLog(r)
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
[C#]
using System;
using System.IO;
class DirAppend
{
public static void Main(String[] args)
{
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.
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();
}
}
Vedere anche
Creazione di un elenco di directory | Lettura e scrittura in un nuovo file di dati | Lettura di testo da un file | Scrittura di testo in un file | Lettura di caratteri da una stringa | Scrittura di caratteri in una stringa | I/O di file di base | StreamWriter | StreamReader | File.AppendText | File.OpenText | StreamReader.ReadLine