Link to home
Start Free TrialLog in
Avatar of TommyTwoPints
TommyTwoPintsFlag for Thailand

asked on

Editing a text file

Hi Experts,

All I want is some simple code that will open an existing text document ("C:\Text.txt") and add 3 lines of code into the text document at line 2;
1)Export=,
2)CEPX,
3)c=test.asc

Thanks Alot,

Tom


ASKER CERTIFIED SOLUTION
Avatar of Olaf_Rabbachin
Olaf_Rabbachin
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Fernando Soto
Hi TommyTwoPints;
Hope this meets your needs.

Dim fileText As String = "C:\Temp\Text.txt"      ' File to edit
Dim fileTemp As String = "C:\Temp\Temp.txt"  ' Temp file write new info to
Dim sr As New StreamReader(fileText)             ' Open the input file
Dim sw As New StreamWriter(fileTemp)            ' Open the temp file
Dim input As String                                        ' Holds input files read info
Dim index As Integer = 1                                ' Used to fine line 2

input = sr.ReadLine()                                     ' Read a line of input
While Not input = Nothing
    If index = 2 Then                                      ' If at line 2 add info
    sw.Write("Export=," & NewLine & "CEPX," & NewLine & "c=test.asc" & NewLine)
    End If
    sw.WriteLine(input)                                   ' Write data to output file
    input = sr.ReadLine()                                ' Get the next line of data
    index += 1                                              ' Add 1 to line number
End While

sr.Close()                                                   ' Close input file
sw.Close()                                                  ' Close output file

File.Delete(fileText)                                     ' Delete original file
File.Move(fileTemp, fileText)                        ' Rename Temp.txt to Text.txt

Good luck
Fernando
Sorry make sure you add the following imports.

Imports System.IO
Imports System.Environment