Read and Write File Example in Vb


Purchase and download the fully updated Visual Basic 2010 edition of this eBook in PDF and ePub for merely $ix.99


In the two previous chapters nosotros looked at accessing databases using Visual Basic. Often, a database provides more than complexity and functionality than is needed and sometimes a plain text file is more plenty for storing information. In this chapter, therefore, we will look at how to work with files and directories in Visual Basic.

Contents


Contents

  • 1 Opening a Text File in Visual Basic
    • 1.1 FileMode Options
    • 1.2 FileAccess Options
    • 1.3 FileShare Options
  • 2 Writing to a File with Visual Basic
  • 3 Reading From a File in Visual Basic
  • 4 Detecting a Change to a File

Opening a Text File in Visual Basic

The first stride in working with files in Visual Basic is to open up the file. This is accomplished using the Visual Basic FileStream class. The FileStream constructor accepts the file name to be opened as the offset parameter, followed by a number of other parameters defining the fashion in which the file is to exist opened. These fall into the categories of FileMode, FileAccess and FileShare. The options bachelor as listed in the following tables:

Ezoic

FileMode Options

<google>ADSDAQBOX_FLOW</google>

Mode Clarification
Append If the file exists information technology is opened. Whatsoever writes are appended to the terminate of the file.
Requires FileAccess.Write mode
Create Creates a new file, removing quondam file if it already exists
CreateNew Creates a new file and returns error if file already exists
Open Opens an existing file. Returns mistake if file does not exist
OpenOrCreate If file already exists it is opened, otherwise a new file is created
Truncate Opens an existing file and deletes all existing content

FileAccess Options

Mode Description
Read Opens the file for reading only.
ReadWrite Opens the file for both reading and writing
Write Opens the file to writing only

FileShare Options

Mode Description
None The file cannot be opened by whatever other plan until it is airtight by the current plan
Read Other programs may simultaneously open and read from the file, but non write to it.
ReadWrite Other programs may simultaneously open and read and write from/to the file.
Write Other programs may simultaneously open and write to the file, just non read from information technology.

With the above options in mind, the following code extract opens 'C:\Temp\text.txt' in FileMode.OpenOrCreate with FileAccess.ReadWrite permission and no file sharing, and then closes information technology:

Dim textFileStream Equally New IO.FileStream("C:\Temp\test.txt", IO.FileMode.OpenOrCreate,             IO.FileAccess.ReadWrite, IO.FileShare.None)  textFileStream.Shut()        

Note that the to a higher place code example assumes that the 'C:\Temp' directory already exists. If it does not, the code will fail. Working with Directories is covered in Working with Directories in Visual Basic.

Writing to a File with Visual Basic

One time a file has been opened with the appropriate options, it can exist written to using the Visual Basic StreamWriter class. The StreamWriter constructor takes a FileStream as the sole parameter.

The Write() and WriteLine() methods of the StreamWriter class are then used to write to the file. Write() writes the text with no new line appended to the terminate of each line. WriteLine() on the other hand, appends a new line to end of each line written to the file.

In the following code excerpt a StreamWriter object is created using the FileStream, and a For loop writes 11 lines to the file:

Dim textFileStream As New IO.FileStream("C:\Temp\exam.txt", IO.FileMode.OpenOrCreate, IO.FileAccess.ReadWrite, IO.FileShare.None)          Dim myFileWriter As New IO.StreamWriter(textFileStream) Dim intCounter Every bit Integer  For intCounter = 0 To 10       myFileWriter.WriteLine("This is line " & CStr(intCounter)) Next intCounter          myFileWriter.Close() textFileStream.Close()        

Note that since the act of closing causes the operating system buffers to be flushed to the file, failing to close the Writer and Stream objects earlier the application exits volition consequence in information written to the file being lost.

Reading From a File in Visual Basic

Now that we have created and written to a file the adjacent stride is to read some information from the file. This is achieved using the Visual Basic StreamReader object.

The StreamReader ReadLine() method can exist used to read the adjacent line from the file stream including the new line. The Read() method reads a line from the file but removes the new line. The ReadToEnd() method can be used to read from the current line in the file to the cease of the file.

The following code excerpt further extends our example to read the data back from the file subsequently it has been written and display the contents in a MessageBox:

          Dim textFileStream As New IO.FileStream("C:\Temp\test.txt", IO.FileMode.OpenOrCreate,                         IO.FileAccess.ReadWrite, IO.FileShare.None)         Dim myFileWriter As New IO.StreamWriter(textFileStream)         Dim myFileReader As New IO.StreamReader(textFileStream)         Dim intCounter Equally Integer         Dim strFileContents Every bit String          For intCounter = 0 To 10             myFileWriter.WriteLine("This is line " & CStr(intCounter))         Next intCounter          strFileContents = myFileReader.ReadToEnd()          MessageBox.Show(strFileContents)          myFileWriter.Close()         myFileReader.Shut()         textFileStream.Close()        

Detecting a Change to a File

A Visual Basic can monitor a file and receive notification from the operating system when the file is inverse by any program. This is achieved using the Visual Basic FileSystemWatcher class.

To effort this, start Visual Studio and create a new Windows Awarding project. Access the Toolbox and double click on the FileSystemWatcher command from the Components section of the list. The new object will appear beneath the Class blueprint surface area with the name FileSystemWatcher1. Select the object and use the Properties panel to change the Path to C:\Temp and the Filter property to test.txt.

Double click on the FileSystemWatcher1 object to admission the event procedure code and modify the changed event as follows:

          Private Sub FileSystemWatcher1_Changed(ByVal sender As System.Object,            ByVal eastward As Arrangement.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Changed          MessageBox.Show("File changed")      End Sub        

Press F5 to build and run the application and, using Notepad, edit and save the file. As soon as the changes are saved, the "File Changed" MessageBox volition appear. Annotation that the NotifyFilter belongings can be used to configure which events trigger an notification.

Now that we take covered file treatment in Visual Basic the adjacent step is to wait at directories in Working with Directories in Visual Bones.

Purchase and download the fully updated Visual Bones 2010 edition of this eBook in PDF and ePub for only $nine.99

frazierlabonall.blogspot.com

Source: https://www.techotopia.com/index.php/Working_with_Files_in_Visual_Basic

0 Response to "Read and Write File Example in Vb"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel