martedì 3 luglio 2012

Replace di una stringa in un file di testo

Ecco un semplice esempio in vb6 di un "replace" di una stringa in un file txt; leggo il contento del file e sostituisco una virgola con un punto.
Sub ReplaceExample()
    Dim strLocal, strChange, pathFile As String
    strLocal = ","
    strChange = "."
    pathFile = "c:\example.txt"
    Dim fso As New FileSystemObject, txtfile, _
    fil1 As File, ts As TextStream
    Set fso = CreateObject("Scripting.FileSystemObject")
    If fso.FileExists(pathFile) = True Then
        Set fil1 = fso.GetFile(pathFile)
    Else
        MsgBox "Percorso file inesistente!"
        Exit Sub
    End If
    strFile = pathFile & "1"
    Open strFile For Output As #1
    ' Legge il contenuto del file e sostituisce 
    ' i separatori decimali.
    Set ts = fil1.OpenAsTextStream(ForReading)
    Do While ts.AtEndOfStream <> True
        Print #1, Replace(ts.ReadAll, strLocal, strChange)
    Loop
    ts.Close
    Close #1
End Sub