📖 Visual Basic 2010 – How to Read Text Files

VB.NET - Reading text files made simple
🔍 Introduction
Reading from a text file in VB.NET is straightforward as long as you know the file's path. It could be stored locally like:
C:\Folder\File.txt
Or it could be located on an external server:
ftp://10.0.0.27/Folder/File.txt
To use these paths in your VB.NET project, simply store them as strings:
Dim LocalFilePath As String = "C:\Folder\File.txt"
Dim WebFilePath As String = "ftp://10.0.0.27/Folder/File.txt"
Note: For remote files, credentials may be required. Unlike local files, which can be read freely, FTP-hosted files often require authentication.
📂 Reading from a Local Text File
- Create a new Windows Forms Application project and save it to
D:\
. - Add a TextBox named
TxtFromFile
(set Multiline = True). - Create a text file named
MyFile.txt
and place it in your project folder (e.g.,D:\WindowsApplication1\Bin\Debug\
). - Add the following content to
MyFile.txt
:Hello Visual Basic Online Course
- Save and close the file.
⚙️ Reading Code Example (Form Load)
' Read a local text file on form load
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim localFilePath As String = Application.StartupPath & "\MyFile.txt"
Dim fileContent As String
If IO.File.Exists(localFilePath) Then
fileContent = My.Computer.FileSystem.ReadAllText(localFilePath, System.Text.Encoding.UTF8)
TxtFromFile.Text = fileContent
Else
MessageBox.Show("File not found: " & localFilePath)
End If
End Sub
🌐 Reading from a Remote Text File (FTP)
If your file is hosted on a remote FTP server, use the following method:
' Reading a remote file from FTP in VB.NET
Imports System.Net
Imports System.IO
Private Sub ReadRemoteFile()
Dim ftpUrl As String = "ftp://example.com/Folder/File.txt"
Dim username As String = "yourUsername"
Dim password As String = "yourPassword"
Try
Dim request As FtpWebRequest = CType(WebRequest.Create(ftpUrl), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.DownloadFile
request.Credentials = New NetworkCredential(username, password)
Using response As FtpWebResponse = CType(request.GetResponse(), FtpWebResponse)
Using responseStream As Stream = response.GetResponseStream()
Using reader As New StreamReader(responseStream)
Dim fileContent As String = reader.ReadToEnd()
TxtFromFile.Text = fileContent
End Using
End Using
End Using
Catch ex As Exception
MessageBox.Show("Error reading remote file: " & ex.Message)
End Try
End Sub
✅ Best Practices
- Encoding: Always specify correct encoding like
UTF-8
to prevent character corruption. - Error Handling: Handle missing or inaccessible files gracefully with alerts.
- Security: Never hardcode sensitive credentials. Use encrypted config files or secure input forms.
📦 Bonus
Check out the full source code example on GitHub:
🔗 View Gist: Read Text File in VB.NET
♥ Here are some online Visual Basic lessons and courses: