The book "Using MicroSoft Visual Basic.net" by Brian Siler and Jeff Spotts (ISBN 0-7897-2572-X, Que, December 2001) gives many insights as to how we can access directories and files. Here are some adapted examples.
The following examples require the first line "Imports System.IO" to be inserted before the first line of the code "PUBLIC CLASS FORM1" so that the objects will be recognized.
Most of the examples use a ListBox called lstFiles to display output. For testing purposes, a button is recommended for each code segment, as some of them require arguments.
Imports System.IO
Private Sub ReadFile(ByVal strFile As String)
' Reads a text file P.C. 2003-12-22
Dim LineBuf As String
Dim InFile As StreamReader = File.OpenText(strFile)
lstFiles.Items.Clear()
Do
LineBuf = InFile.ReadLine()
If LineBuf Is Nothing Then
Exit Do
End If
Debug.WriteLine(LineBuf)
lstFiles.Items.Add(LineBuf)
Loop
InFile.Close()
End Sub
Imports System.IO
Private Sub WriteFile(ByVal strInfile As String, ByVal strOutFile As String)
' Reads, modifies and writes a text file P.C. 2003-12-22
Dim InFile As StreamReader = File.OpenText(strInfile)
' The output file is written in append mode
Dim OutFile As StreamWriter = File.AppendText(strOutFile)
Dim LineBuf As String
'Following line is required if file read more than once
'InFile.BaseStream.Seek(0, SeekOrigin.Begin)
lstFiles.Items.Clear()
While InFile.Peek() <> -1
LineBuf = InFile.ReadLine() ' read a line
OutFile.WriteLine(LineBuf.ToUpper) ' write in uppercase
lstFiles.Items.Add(LineBuf.ToUpper)
End While
InFile.Close()
OutFile.Close()
End Sub
Imports System.IO
Private Sub FileDirInfo(ByVal strDir As String)
' lists files and dir of a given directory strDir P.C. 2003-12-22
Dim dirTmp As DirectoryInfo
Dim fsiTmp As FileSystemInfo
dirTmp = New DirectoryInfo(strDir)
lstFiles.Items.Clear()
For Each fsiTmp In dirTmp.GetFileSystemInfos()
If fsiTmp.GetType() Is GetType(DirectoryInfo) Then
lstFiles.Items.Add("Dir.:" & fsiTmp.Name)
' Do processing required for a directory, recursion, etc.
Else
lstFiles.Items.Add("File:" & fsiTmp.Name)
' Do processing for a file
End If
Next
End Sub
Imports System.IO
Private Sub SubDirInfo(ByVal strDir As String) 'uses recursion
'Files, dir. and sub-dir of a given dir. P.C. 2003-12-23
'Notice that the file list does not always follow the directory
Dim dirTmp As DirectoryInfo
Dim fsiTmp As FileSystemInfo
dirTmp = New DirectoryInfo(strDir)
lstFiles.Items.Add(dirTmp.FullName)
For Each fsiTmp In dirTmp.GetFileSystemInfos()
If fsiTmp.GetType() Is GetType(DirectoryInfo) Then
' Do additional processing required
SubDirInfo(fsiTmp.FullName)
Else
' Do processing for a file
' Here we display the file name, size and creation date
' Other properties can be displayed as required
Dim strInfo As String = " " & fsiTmp.Name & " "
strInfo &= CType(fsiTmp, FileInfo).Length.ToString & " "
strInfo &= fsiTmp.CreationTime.ToString & " "
lstFiles.Items.Add(strInfo)
End If
Next
lstFiles.Items.Add(vbCrLf) 'blank line to delimit dir
End Sub
Imports System.IO
Private Sub FileAtt(ByVal strFile As String) '5. attributes
'This examples sets a file to readonly mode P.C. 2003-12-23
' File Name input can be solicited in the calling proc. using
' Dim strFile as string=InputBox("Enter File Name:")
Dim fioFile As FileInfo = New FileInfo(strFile)
If fioFile.Attributes And FileAttributes.ReadOnly Then
MessageBox.Show("File " & strFile & " is already readonly")
Else
fioFile.Attributes = fioFile.Attributes Or FileAttributes.ReadOnly
MessageBox.Show("File " & strFile & " has been set to readonly")
End If
End Sub
Imports System.IO
Private Sub FileOper() '6. Misc. File Operations
'
Dim strOldF As String = "C:\tmp\TestFile.txt"
Dim strNewF As String = "c:\tmp\TestFileCopy.txt"
Dim strNewF1 As String = "c:\tmp\TestFileCopyNew.txt"
' Create a new file
Dim OutFile As StreamWriter = File.CreateText(strOldF)
OutFile.WriteLine("This is a Test")
OutFile.Close()
' filTmp = strOldF
Dim filTmp As New FileInfo(strOldF)
' COPY using FileInfo.CopyTo() method
filTmp.CopyTo(strNewF, True) ' make a copy, overwrite if necessary
If File.exists(strNewF) Then
lstFiles.items.add(strNewF & " exists")
' COPY using File.Copy() method
File.Copy(strOldF, strNewF, True)
End If
Dim filCopy As New FileInfo(strNewF)
' RENAME using FileInfo.MoveTo() method
filCopy.MoveTo(strNewF1) 'rename file
Dim filCopy1 As New FileInfo(strNewF1)
' DELETE using FileInfo.Delete() method
filCopy1.Delete() 'file strNewF1
' DELETE using File.Delete(strPath) method
File.Delete(strOldF) ' file strOldF
End Sub
Imports System.io
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If Trim(TextBox1.Text).Length = 0 Then Return
' Textbox2 contains directory name
Dim dir1 As DirectoryInfo = New DirectoryInfo(TextBox2.Text) 'tb2=dir. name
' Textbox1 contains File names, wildcards permitted
Dim fsi1() As FileSystemInfo = dir1.GetFileSystemInfos(TextBox1.Text)
Dim intI As Integer
For intI = 0 To fsi1.Length - 1
ListBox1.Items.Add(fsi1(intI).Name & " " & fsi1(intI).LastWriteTime().ToString)
Next
End Sub
Textbox example
Imports System.IO
' PC 2004-08-20
' ========================================
' module-level variable for name of file
Dim strFile As String = "TestText.txt"
'=========================================
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' The output file is written in the same file
Dim tFile As StreamWriter = File.CreateText(strFile)
tFile.WriteLine(TextBox1.Text)
tFile.Close()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Populate textbox1 on program load
Dim tFile As StreamReader = File.OpenText(strFile)
TextBox1.Text = tFile.ReadLine()
tFile.Close()
End Sub
Updated 2004-08-20