Are you saying that you have a bunch of lines that added in succesion instead of one line? Try using the StreamWriter class. I have used it on a number of occassions to write text to a file and I have had no problems.
Thanks for your help. I've tried using the StreamWriter class and it creates the file and writes to it with no problem. I haven't figured out how to append to it using the StreamWriter class. Using ohter methods as stated in my initial post, the outcome was as you've stated: "Are you saying that you have a bunch of lines that added in succesion instead of one line? " Let me eplain to you what I need to do. I have an app that I put together to perform remote tasks. I want to be able to type in the host name in a textbox, save it to a text file, and append the text file every time I type in a new host name only if the host name doesn't already exist.
Open the TextFile, read the Contents, and check if the Hotsname is already present... else add.. check this code:
Dim sw As System.IO.TextReader
sw = System.IO.File.OpenText("C:\MyTextFile.txt")
Dim MyContents As String = sw.ReadToEnd
If Instr(MyContents,Text1.Text) = 0 Then
' Text does not contain the name
sw = IO.File.AppendText("C:\MyTextFile.txt")
Dim sw as StreamWriter
sw = File.AppendText(txtFileName.Text)
Catch exc As Exception
If Not sw Is Nothing Then
It turns out that the code you've provided was helpful. I've just used the StreamReader class instead.
Dim sw As StreamWriter Dim sr As System.IO.StreamReader If File.Exists("D:\HostFile.txt") Then sr = System.IO.File.OpenText("D:\HostFile.txt") Dim MyContents As String = sr.ReadToEnd sr.Close() If InStr(MyContents, t_HostName.Text) = 0 Then
sw = New StreamWriter("D:\Hostfile.txt", True) 'True for appending sw.WriteLine(Me.t_HostName.Text) sw.Flush() sw.Close() End If Else
'Pass the file path and the file name to the StreamWriter constructor. sw = New StreamWriter("D:\Hostfile.txt", True) 'True for appending sw.WriteLine(Me.t_HostName.Text) 'Close the file. sw.Flush() sw.Close() End If