File I/O in VB.NET
File input and output (I/O) operations are fundamental to many applications. VB.NET provides robust classes and methods within the System.IO
namespace to handle file operations efficiently and safely.
Reading from Files
Reading Entire File Content
The File.ReadAllText
method reads the entire content of a text file into a single string.
Example: ReadAllText
Imports System.IO
Module FileReadExample
Sub Main()
Dim filePath As String = "C:\path\to\your\file.txt"
Try
If File.Exists(filePath) Then
Dim fileContent As String = File.ReadAllText(filePath)
Console.WriteLine("File Content:")
Console.WriteLine(fileContent)
Else
Console.WriteLine($"File not found: {filePath}")
End If
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End Module
Reading File Line by Line
For larger files, reading line by line is more memory-efficient. File.ReadAllLines
reads all lines into a string array, and File.ReadLines
returns an enumerable collection.
Example: ReadAllLines
Imports System.IO
Module FileReadLinesExample
Sub Main()
Dim filePath As String = "C:\path\to\your\file.txt"
Try
If File.Exists(filePath) Then
Dim lines As String() = File.ReadAllLines(filePath)
Console.WriteLine("File Content (Line by Line):")
For Each line As String In lines
Console.WriteLine(line)
Next
Else
Console.WriteLine($"File not found: {filePath}")
End If
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End Module
Using StreamReader
The StreamReader
class provides more control over reading text files, allowing you to read character by character, line by line, or the entire stream.
Example: StreamReader
Imports System.IO
Module StreamReaderExample
Sub Main()
Dim filePath As String = "C:\path\to\your\file.txt"
Try
If File.Exists(filePath) Then
Using reader As New StreamReader(filePath)
Dim line As String
Console.WriteLine("Reading with StreamReader:")
Do While (line = reader.ReadLine()) IsNot Nothing
Console.WriteLine(line)
Loop
End Using
Else
Console.WriteLine($"File not found: {filePath}")
End If
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End Module
Writing to Files
Writing to a File
The File.WriteAllText
method writes a string to a file, overwriting the file if it exists or creating it if it doesn't.
Example: WriteAllText
Imports System.IO
Module FileWriterExample
Sub Main()
Dim filePath As String = "C:\path\to\your\output.txt"
Dim contentToWrite As String = "This is the first line." & Environment.NewLine & "This is the second line."
Try
File.WriteAllText(filePath, contentToWrite)
Console.WriteLine($"Successfully wrote to {filePath}")
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End Module
Appending to a File
Use File.AppendAllText
to add content to the end of an existing file.
Example: AppendAllText
Imports System.IO
Module FileAppendExample
Sub Main()
Dim filePath As String = "C:\path\to\your\output.txt"
Dim contentToAppend As String = "This line is appended." & Environment.NewLine
Try
File.AppendAllText(filePath, contentToAppend)
Console.WriteLine($"Successfully appended to {filePath}")
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End Module
Using StreamWriter
The StreamWriter
class allows for more granular control over writing to text files, including specifying encoding.
Example: StreamWriter
Imports System.IO
Imports System.Text
Module StreamWriterExample
Sub Main()
Dim filePath As String = "C:\path\to\your\stream_output.txt"
Dim linesToWrite As String() = {"Line 1", "Line 2", "Line 3"}
Try
' Using Statement ensures the stream is properly closed and disposed
Using writer As New StreamWriter(filePath, False, Encoding.UTF8) ' False to overwrite
For Each line As String In linesToWrite
writer.WriteLine(line)
Next
writer.Write("This is a final note.")
End Using
Console.WriteLine($"Successfully wrote with StreamWriter to {filePath}")
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End Module
Working with Directories
Creating and Deleting Directories
Directory.CreateDirectory
creates a directory, and Directory.Delete
removes one.
Example: Directory Operations
Imports System.IO
Module DirectoryExample
Sub Main()
Dim dirPath As String = "C:\path\to\new_directory"
Try
' Create directory
Directory.CreateDirectory(dirPath)
Console.WriteLine($"Directory created: {dirPath}")
' Example of deleting a directory (use with caution!)
' If Directory.Exists(dirPath) Then
' Directory.Delete(dirPath, True) ' True to delete non-empty directory
' Console.WriteLine($"Directory deleted: {dirPath}")
' End If
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End Module
Listing Files and Directories
Directory.GetFiles
and Directory.GetDirectories
retrieve lists of files and subdirectories.
Example: Listing Contents
Imports System.IO
Module ListDirectoryExample
Sub Main()
Dim targetDirectory As String = "C:\path\to\your\directory" ' e.g., "C:\Windows"
Try
If Directory.Exists(targetDirectory) Then
Console.WriteLine($"Files in {targetDirectory}:")
Dim files As String() = Directory.GetFiles(targetDirectory)
For Each file As String In files
Console.WriteLine(Path.GetFileName(file))
Next
Console.WriteLine($"Subdirectories in {targetDirectory}:")
Dim directories As String() = Directory.GetDirectories(targetDirectory)
For Each dir As String In directories
Console.WriteLine(Path.GetFileName(dir))
Next
Else
Console.WriteLine($"Directory not found: {targetDirectory}")
End If
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End Module
File Paths
The System.IO.Path
class provides utility methods for manipulating path strings, such as getting file extensions, names, or combining paths.
Example: Path Utilities
Imports System.IO
Module PathUtilityExample
Sub Main()
Dim fullPath As String = "C:\Documents\MyProject\MyFile.vb"
Console.WriteLine($"Full Path: {fullPath}")
Console.WriteLine($"Directory: {Path.GetDirectoryName(fullPath)}")
Console.WriteLine($"File Name: {Path.GetFileName(fullPath)}")
Console.WriteLine($"File Name Without Extension: {Path.GetFileNameWithoutExtension(fullPath)}")
Console.WriteLine($"Extension: {Path.GetExtension(fullPath)}")
Dim combinedPath As String = Path.Combine("C:\Temp", "Data", "report.csv")
Console.WriteLine($"Combined Path: {combinedPath}")
End Sub
End Module
Best Practices
- Always use
Try...Catch
blocks to handle potential exceptions during file operations (e.g., file not found, access denied). - Use the
Using
statement withStreamReader
andStreamWriter
to ensure resources are properly disposed of, even if errors occur. - Check if files or directories exist before attempting operations like reading, writing, or deleting to prevent exceptions.
- Be mindful of file permissions and run your application with appropriate privileges.
- For binary file operations, consider using classes like
FileStream
,BinaryReader
, andBinaryWriter
.