Writing to text file

S

Saga

Hi all! Using VB 2008.

I need to write to a text file. Create and write if it does not exist
or append if it does. I have this code:

If System.IO.File.Exists("G:\work\temp\TestTxtFiles\Box\testfile.txt")
Then
'Open file for append.
Using oFile As System.IO.StreamWriter =
System.IO.File.AppendText("G:\work\temp\TestTxtFiles\Box\testfile.txt")
oFile.WriteLine("Test file line 4")
oFile.WriteLine("Test file line 5")
oFile.WriteLine("Test file line 6")
oFile.Close()
End Using
Else
'Create a test text file.
Using oFile As System.IO.StreamWriter =
System.IO.File.CreateText("G:\work\temp\TestTxtFiles\Box\testfile.txt")
oFile.WriteLine("Table CODES")
oFile.WriteLine("Test file line 1")
oFile.WriteLine("Test file line 2")
oFile.WriteLine("Test file line 3")
oFile.Close()
End Using
End If

It works. My question is whether this is the best way to do this or if there
is
a more optimized method. Thanks! Saga
 
F

Family Tree Mike

Hi all! Using VB 2008.

I need to write to a text file. Create and write if it does not exist
or append if it does. I have this code:

If System.IO.File.Exists("G:\work\temp\TestTxtFiles\Box\testfile.txt")
Then
'Open file for append.
Using oFile As System.IO.StreamWriter =
System.IO.File.AppendText("G:\work\temp\TestTxtFiles\Box\testfile.txt")
oFile.WriteLine("Test file line 4")
oFile.WriteLine("Test file line 5")
oFile.WriteLine("Test file line 6")
oFile.Close()
End Using
Else
'Create a test text file.
Using oFile As System.IO.StreamWriter =
System.IO.File.CreateText("G:\work\temp\TestTxtFiles\Box\testfile.txt")
oFile.WriteLine("Table CODES")
oFile.WriteLine("Test file line 1")
oFile.WriteLine("Test file line 2")
oFile.WriteLine("Test file line 3")
oFile.Close()
End Using
End If

It works. My question is whether this is the best way to do this or if there
is
a more optimized method. Thanks! Saga

AppendText creates the file if it is not found, so you don't need the
check, nor two branches. Just use AppendText and skip the CreateText
routine.
 
S

Saga

AppendText creates the file if it is not found, so you don't need the
check, nor two branches. Just use AppendText and skip the CreateText
routine.
Thanks for the tip, much appreciated! I will make the corresponding change
to my code. Saga
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top