Showing posts with label File. Show all posts
Showing posts with label File. 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.

Reading data from a Sequential Access File

HOW TO: Declare a StreamReader Variable
Syntax
{Dim | Private} streamReaderVariableName As IO.StreamReader

Example
Dim inFile As IO.StreamReader
declares a StreamReader variable named inFile.

HOW TO: Create a StreamReader Object
Syntax
IO.File.OpenText(fileName)

Example
inFile = IO.File.OpenText(“report.txt”)
opens the report.txt file for input, creates a StreamReader object and assigns it to the inFile variable.

HOW TO: Read data from a sequential access file
Syntax
streamReaderVariableName.ReadLine

Example
Dim message As String
message = inFile.ReadLine
reads a line of text from the file associated with the inFile variable and assigns the line, excluding the newline character, to the message variable.

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.