2009-08-26 10 views
7

Come si codifica l'algoritmo di seguito in VB.NET?Creazione/modifica di file di testo tramite VB.NET

Procedure logfile() 
{ 
    if "C:\textfile.txt"=exist then 
     open the textfile; 
    else 
     create the textfile; 
    end if 
    go to the end of the textfile; 
    write new line in the textfile; 
    save; 
    close; 
} 

risposta

12
Dim FILE_NAME As String = "C:\textfile.txt" 
Dim i As Integer 
Dim aryText(4) As String 

aryText(0) = "Mary WriteLine" 
aryText(1) = "Had" 
aryText(2) = "Another" 
aryText(3) = "Little" 
aryText(4) = "One" 

Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True) 

For i = 0 To 4 
    objWriter.WriteLine(aryText(i)) 
Next 

objWriter.Close() 
MsgBox("Text Appended to the File") 

Se si imposta il secondo parametro per True nel costruttore 's il System.IO.StreamWriter si aggiungerà un file se esiste già, o di crearne uno nuovo se non lo fa.

2

È preferibile utilizzare un componente che esegue questo tipo di accesso fuori dalla scatola. Il Logging Application Block da Enterprise Library per esempio. In questo modo, ottieni flessibilità, scalabilità e non hai contesa con il tuo file di registro.

Per rispondere alla tua domanda in particolare (mi dispiace, non so VB, ma la traduzione dovrebbe essere abbastanza semplice) ...

void Main() 
{ 
    using(var fs = File.Open(@"c:\textfile.txt", FileMode.Append)) 
    { 
     using(var sw = new StreamWriter(fs)) 
     { 
      sw.WriteLine("New Line"); 
      sw.Close(); 
     } 

     fs.Close(); 
    } 
} 
8

Ciò può essere ottenuto in una sola linea troppo:

System.IO.File.AppendAllText(filePath, "Hello World" & vbCrLf) 

Creerà il file se mancante, aggiunge il testo e lo chiude di nuovo.

Vedere MSDN, File.AppendAllText Method.

+0

molto semplice e pulito –