Sei sulla pagina 1di 4

Cmo: Leer archivos de texto

delimitado por comas en


Visual Basic
El objeto TextFieldParser proporciona un mtodo para analizar de forma sencilla y eficaz archivos
de texto estructurados, como registros. La propiedadTextFieldType define si se trata de un archivo
delimitado o uno con campos de ancho fijo de texto.
Para analizar un archivo de texto delimitado por comas
1. Cree un nuevo objeto TextFieldParser. El cdigo siguiente crea el
objeto TextFieldParser denominado MyReader y abre el archivo test.txt.
VB
Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser _
("C:\TestFolder\test.txt")

2. Defina el tipo de TextField y el delimitador. El cdigo siguiente define la
propiedad TextFieldType como Delimited y el delimitador como ",".
VB
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")

3. Recorra los campos del archivo. Si alguna lnea est daada, cree un informe de error y
contine el anlisis. El cdigo siguiente recorre el archivo para mostrar cada campo a la vez
e indica los campos con formato incorrecto.
VB

Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As _
Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try

4. Cierre los bloques While y Using con End While y End Using.
VB
End While
End Using

Ejemplo
En este ejemplo se lee el archivo test.txt.
VB
Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While
End Using

Cmo: Escribir texto en
archivos en Visual Basic
El My.Computer.FileSystem.WriteAllText (Mtodo) se puede utilizar para escribir el texto en archivos.
Si el archivo especificado no existe, se crea.
Procedimiento
Para escribir texto en un archivo.
Utilice el mtodo WriteAllText para escribir el texto en un archivo, especificando el archivo
y el texto que se va a escribir. Este ejemplo escribe la lnea "This is new text." en el
archivo llamado test.txt, anexando el texto al texto existente en el archivo.
VB
My.Computer.FileSystem.WriteAllText("C:\TestFolder1\test.txt", _
"This is new text to be added.",True)

Para escribir una serie de cadenas en un archivo
Recorra en iteracin la coleccin de cadenas. Utilice el mtodo WriteAllText para escribir el
texto en un archivo, especificando el archivo de destino, la cadena que se debe agregar y
estableciendo append en True.
Este ejemplo escribe los nombres de los archivos contenidos en el directorio Documents
and Settings en el archivo FileList.txt, insertando un retorno de carro entre cada
uno de ellos para una mejor legibilidad.
VB
For Each foundFile As String In _
My.Computer.FileSystem.GetFiles("C:\Documents and Settings")
foundFile = foundFile & vbCrLf
My.Computer.FileSystem.WriteAllText _
("C:\Documents and Settings\FileList.txt", foundFile, True)
Next

Cmo: Anexar a archivos de
texto en Visual Basic
My.Computer.FileSystem.WriteAllText (Mtodo) se puede utilizar para anexar a un archivo de texto
especificando que el parmetro append se establece enTrue.
Para anexar a un archivo de texto
Utilice el mtodo WriteAllText, especificando el archivo de destino y la cadena que se va a
anexar y estableciendo el parmetro append en True.
Este ejemplo escribe la cadena "This is a test string." en el
archivo Testfile.txt.
VB
Dim inputString As String = "This is a test string."
My.Computer.FileSystem.WriteAllText _
("C://testfile.txt", inputString, True)

Potrebbero piacerti anche