2009-08-26 11 views
7

¿Cómo se codifica el algoritmo que se muestra a continuación en VB.NET?Creación/edición de archivos de texto a través de 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; 
} 

Respuesta

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") 

Si ajusta el segundo parámetro a True en el constructor del System.IO.StreamWriter 's se añadirá a un archivo si ya existe, o crear uno nuevo si no lo hace.

2

Lo mejor es usar un componente que hace este tipo de sesión fuera de la caja. El Logging Application Block de Enterprise Library por ejemplo. De esta forma, obtienes flexibilidad, escalabilidad y no tienes conflictos con tu archivo de registro.

Para responder a su pregunta específica (lo siento, no sé VB, pero la traducción debe ser lo suficientemente simple) ...

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

Esto se puede lograr en una sola línea también:

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

Creará el archivo si falta, anexará el texto y lo cerrará nuevamente.

Consulte MSDN, File.AppendAllText Method.

+0

muy simple y limpio –

Cuestiones relacionadas