Prev: Progress bar and system thread
Next: ctype question.
From: Saga on 1 Mar 2010 17:50 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
From: Family Tree Mike on 1 Mar 2010 18:10 On 3/1/2010 5:50 PM, Saga wrote: > 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. -- Mike
From: Saga on 2 Mar 2010 12:53 > 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 > -- > Mike
|
Pages: 1 Prev: Progress bar and system thread Next: ctype question. |