Write to a Text File

Article Tools

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

clip_image002

 

Previous postVS2008 & PDM.DLL dramatically improves QTP’s debug engine Next postCreating a Text File

Related Posts

Post Your Comment

You must be logged in to post a comment.