Write to a Text File
Posted by admin - Mar 31, 2008 Articles, Dani Vainstein, QTips, Text Files 0 0 Views : 254 Receive Updates For This Category
Article Tools
- Print this page
- Add Comment
- Send to Friend
- Last Updated on :
Jul 16, 2011
System.IO.File class provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.
The System.IO.StreamWriter class implements a TextWriter for writing characters to a stream in a particular encoding.
The following code examples show how to write text to a text file.
The first example shows how to add text to an existing file. The second example shows how to create a new text file and write a string to it. Similar functionality can be provided by the WriteAllText methods.
Option Explicit
Const FNAME = "C:\TestFile.txt"
Dim sw
' ** Create an instance of StreamWriter to write text to a file.
Set sw = DotNetFactory.CreateInstance("System.IO.StreamWriter",, FNAME )
' ** Add some text to the file.
sw.Write("This is the ")
sw.WriteLine("header for the file.")
sw.WriteLine("-------------------")
' ** Arbitrary objects can also be written to the file.
sw.Write("The date is: ")
sw.WriteLine( DotNetFactory.CreateInstance( "System.DateTime" ).Now )
sw.Close()
Option Explicit
Const FILE_NAME = "C:\MyFile.txt"
Dim ioFile, sw
Set ioFile = DotNetFactory.CreateInstance( "System.IO.File" )
If Cbool( ioFile.Exists( FILE_NAME ) ) Then
Print FILE_NAME & " already exists."
Else
Set sw = ioFile.CreateText( FILE_NAME )
sw.WriteLine("This is my file.")
sw.WriteLine("I can write ints {0} or floats {1}, and so on.",1,4.2)
sw.Close()
End If


