VB.NET

File Manipulations

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.

1. Read a text file


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

2. Read, modify and write a text file

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

3. Process all files and directories in a given directory


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

4. Process files, directories and subdirectories in a given directory


This is a recursive procedure that calls itself to accomplish the task.
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

5. File attributes


File attributes describe the properties of each file, and these attributes may be displayed or changed using the .Attributes property of the FileInfo object. Each attribute occupies one bit in a two-byte storage, so that individual properties may be extracted with an AND operator, and my be set with an OR operator.
Frequently used properties under System.IO.FileAttributes are:
archive, compressed, directory, hidden, normal, readonly
The following example illustrates how to get and set the readonly attribute.
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

6. Copy, rename, delete


These are methods of the FILE class: File.Copy(), File.Move(), File.Moveto(), File.Delete().
The FileInfo class also allows some file operations, such as: filFile.CopyTo(), filFile.MoveTo()



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

7. Display file creation dates


The DirectoryInfo class and the FileSystemInfo class together provide means of extracting file information, such as creation dates, last write time, last access time, etc. Wild cards are allowed in the file specifications (textbox1). The directory is entered in textbox2.

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

8. Store contents of textbox in a file


This example populates a textbox from a file on program load, and rewrites the contents (modified or not) back on a button-click. User can modify the code to automatically save the contents on exit.

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