Showing posts with label Write. Show all posts
Showing posts with label Write. Show all posts

Wednesday, November 3, 2010

Determine whether a Sequential Access File Exists

HOW TO: Determine whether a Sequential Access File Exists
Syntax
IO.File.Exists(fileName)

Example
If IO.File.Exists(“report.txt”)  = True Then
determines whether the report.txt file exists in the current project’s bin\Debug folder.

Close an Output Sequential Access File

HOW TO: Close an Output Sequential Access File
Syntax
streamWriterVariableName.Close()

Example
outFile.Close()
closes the file associated with the outFile variable.

Write data to a sequential access file

HOW TO: Write data to a sequential access file using StreamWriter
Syntax
streamWriterVariableName.Write(data)
streamWriterVariableName.WriteLine(data)

Example 1
outFile.write(“Hello”)

Result
The string “Hello” is written to the file, the next character written to the file will appear immediatley after the letter “o”.

Example 2
outFile.WriteLine(“Hello”)

Result
The string “Hello” is written to the file. The next character written to the file will appear on the next line.

StreamWriter object

HOW TO: Declare a StreamWriter object
Syntax
{Dim | Private} streamWriterVariableName As IO.StreamWriter

Example
Dim outFile As IO.StreamWriter
declares a StreamWriter variable named outFile

HOW TO: Create a StreamWriter object
Syntax
IO.File.method(fileName)

Methods
CreateText: opens a file for output - creates a new empty file to which data can be written. If the file already exists, the data in the file is deleted before any new data is written to it.

AppendText: opens a file for append - the new data is written after any existing data in the file. If the file does not exist, the file is created for you.

Example 1
outFile = IO.File.CreateText(“mytextfile.txt”)
opens the mytextfile.txt file for output; creates a StreamWriter object and assigns it to the outFile variable. The file is open for output.

Example 2
outFile = IO.File.AppendText(“report.txt”)
opens the report.txt file for append; creates a StreamWriter object and assigns it to the outFile variable. The file is open for append.