逐步解說:在 Visual Basic 中管理檔案和目錄

本逐步解說提供 Visual Basic 中檔案 I/O 的基本概念簡介。 其中說明如何建立一個小型應用程式,以提列並檢查目錄中的文字檔案。 針對每個選取的文字檔案,應用程式會提供檔案屬性和第一行內容。 您也可以選擇將資訊寫入記錄檔。

本逐步解說使用 Visual Basic 所提供的 My.Computer.FileSystem Object 成員。 如需相關資訊,請參閱 FileSystem 。 本逐步解說最後會提供使用來自 System.IO 命名空間之類別的對等範例。

注意

在下列指示的某些 Visual Studio 使用者介面項目中,您的電腦可能會顯示不同的名稱或位置: 您所擁有的 Visual Studio 版本以及使用的設定會決定這些項目。 如需詳細資訊,請參閱將 Visual Studio IDE 個人化

建立專案

  1. 按一下 [檔案] 功能表上的 [新增專案]。

    [新增專案] 對話方塊隨即出現。

  2. 在 [已安裝的範本] 窗格中,展開 [Visual Basic],然後按一下 [Windows]。 在中間的 [範本] 窗格中,按一下 [Windows Forms 應用程式]。

  3. 在 [名稱] 方塊中,輸入 FileExplorer 以設定專案名稱,然後按一下 [確定]。

    Visual Studio 即會將專案新增至 [方案總管],並開啟 [Windows Forms 設計工具]。

  4. 將下表的控制項新增至表單,並設定其屬性的對應值。

    控制 屬性
    ListBox 名稱 filesListBox
    按鈕 名稱

    Text
    browseButton

    瀏覽
    按鈕 名稱

    Text
    examineButton

    檢查
    CheckBox 名稱

    Text
    saveCheckBox

    儲存結果
    FolderBrowserDialog 名稱 FolderBrowserDialog1

若要選取資料夾,並列出資料夾中的檔案

  1. 按兩下表單的控制項,以建立 browseButtonClick 事件處理常式。 [程式碼編輯器] 隨即開啟。

  2. 將下列程式碼加入至 Click 事件處理常式。

    If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
        ' List files in the folder.
        ListFiles(FolderBrowserDialog1.SelectedPath)
    End If
    

    FolderBrowserDialog1.ShowDialog 呼叫會開啟 [瀏覽資料夾] 對話方塊。 使用者按一下 [確定] 之後,系統會以引數形式將 SelectedPath 屬性傳送給 ListFiles 方法,以在下一個步驟中加入。

  3. 新增下列 ListFiles 方法。

    Private Sub ListFiles(ByVal folderPath As String)
        filesListBox.Items.Clear()
    
        Dim fileNames = My.Computer.FileSystem.GetFiles(
            folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.txt")
    
        For Each fileName As String In fileNames
            filesListBox.Items.Add(fileName)
        Next
    End Sub
    

    此程式碼會先清除 ListBox

    GetFiles 方法接著會擷取一組字串,目錄中每個檔案一個字串。 GetFiles 方法可接受搜尋模式引數,以擷取符合特定模式的檔案。 在此範例中,僅會傳回副檔名為 .txt 的檔案。

    隨即將 GetFiles 方法所傳回的字串新增至 ListBox

  4. 執行應用程式。 按一下 [ 瀏覽 ] 按鈕。 在 [瀏覽資料夾] 對話方塊中,瀏覽至包含 .txt 檔案的資料夾,然後選取資料夾並按一下 [確定]。

    ListBox 包含所選資料夾中的 .txt 檔案清單。

  5. 停止執行應用程式。

若要取得檔案的屬性以及文字檔案的內容

  1. 按兩下表單的控制項,以建立 examineButtonClick 事件處理常式。

  2. 將下列程式碼加入至 Click 事件處理常式。

    If filesListBox.SelectedItem Is Nothing Then
        MessageBox.Show("Please select a file.")
        Exit Sub
    End If
    
    ' Obtain the file path from the list box selection.
    Dim filePath = filesListBox.SelectedItem.ToString
    
    ' Verify that the file was not removed since the
    ' Browse button was clicked.
    If My.Computer.FileSystem.FileExists(filePath) = False Then
        MessageBox.Show("File Not Found: " & filePath)
        Exit Sub
    End If
    
    ' Obtain file information in a string.
    Dim fileInfoText As String = GetTextForOutput(filePath)
    
    ' Show the file information.
    MessageBox.Show(fileInfoText)
    

    程式碼會驗證 ListBox 中已選取項目。 接著,它會從 ListBox 取得檔案路徑的項目。 FileExists 方法用來檢查檔案是否仍然存在。

    系統會以引數形式將檔案路徑傳送給 GetTextForOutput 方法,以在下一個步驟中加入。 這個方法會傳回字串,其中包含檔案資訊。 MessageBox 中會顯示檔案資訊。

  3. 新增下列 GetTextForOutput 方法。

    Private Function GetTextForOutput(ByVal filePath As String) As String
        ' Verify that the file exists.
        If My.Computer.FileSystem.FileExists(filePath) = False Then
            Throw New Exception("File Not Found: " & filePath)
        End If
    
        ' Create a new StringBuilder, which is used
        ' to efficiently build strings.
        Dim sb As New System.Text.StringBuilder()
    
        ' Obtain file information.
        Dim thisFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath)
    
        ' Add file attributes.
        sb.Append("File: " & thisFile.FullName)
        sb.Append(vbCrLf)
        sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
        sb.Append(vbCrLf)
        sb.Append("Size: " & thisFile.Length.ToString & " bytes")
        sb.Append(vbCrLf)
    
        ' Open the text file.
        Dim sr As System.IO.StreamReader =
            My.Computer.FileSystem.OpenTextFileReader(filePath)
    
        ' Add the first line from the file.
        If sr.Peek() >= 0 Then
            sb.Append("First Line: " & sr.ReadLine())
        End If
        sr.Close()
    
        Return sb.ToString
    End Function
    

    程式碼使用 GetFileInfo 方法來取得檔案參數。 檔案參數會新增至 StringBuilder

    OpenTextFileReader 方法會將檔案內容讀入 StreamReader。 系統會由 StreamReader 取得第一行的內容,並將其新增至 StringBuilder

  4. 執行應用程式。 按一下 [瀏覽],並瀏覽至包含 .txt 檔案的資料夾。 按一下 [確定]

    選取 ListBox 中的檔案,然後按一下 [檢查]MessageBox 隨即顯示檔案資訊。

  5. 停止執行應用程式。

若要新增記錄項目

  1. 將下列程式碼加入 examineButton_Click 事件處理常式的結尾。

    If saveCheckBox.Checked = True Then
        ' Place the log file in the same folder as the examined file.
        Dim logFolder As String = My.Computer.FileSystem.GetFileInfo(filePath).DirectoryName
        Dim logFilePath = My.Computer.FileSystem.CombinePath(logFolder, "log.txt")
    
        Dim logText As String = "Logged: " & Date.Now.ToString &
            vbCrLf & fileInfoText & vbCrLf & vbCrLf
    
        ' Append text to the log file.
        My.Computer.FileSystem.WriteAllText(logFilePath, logText, append:=True)
    End If
    

    程式碼會將記錄檔路徑設為將記錄檔放入所選檔案的相同目錄中。 記錄項目的文字則會設為目前的日期和時間,後面接著檔案資訊。

    append 引數設定為 TrueWriteAllText 方法用來建立記錄項目。

  2. 執行應用程式。 瀏覽至文字檔案,在 ListBox 中加以選取,並選取 [儲存結果] 核取方塊,然後按一下 [檢查]。 確認記錄項目已寫入 log.txt 檔案。

  3. 停止執行應用程式。

若要使用目前的目錄

  1. 按兩下表單的控制項,以建立 Form1_Load 的事件處理常式。

  2. 將下列程式碼加入至 事件處理常式。

    ' Set the default directory of the folder browser to the current directory.
    FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory
    

    此程式碼會將資料夾瀏覽器的預設目錄設為目前的目錄。

  3. 執行應用程式。 當您首次按一下 [瀏覽] 時,[瀏覽資料夾] 對話方塊即會開啟至目前目錄。

  4. 停止執行應用程式。

若要選擇性地啟用控制項

  1. 新增下列 SetEnabled 方法。

    Private Sub SetEnabled()
        Dim anySelected As Boolean =
            (filesListBox.SelectedItem IsNot Nothing)
    
        examineButton.Enabled = anySelected
        saveCheckBox.Enabled = anySelected
    End Sub
    

    SetEnabled 方法會依據 ListBox 中是否選取項目,來啟用或停用控制項。

  2. 按兩下表單的 ListBox 控制項,以建立 filesListBoxSelectedIndexChanged 事件處理常式。

  3. 在新的 filesListBox_SelectedIndexChanged 事件處理常式中,新增 SetEnabled 的呼叫。

  4. browseButton_Click 事件處理常式結尾,新增 SetEnabled 的呼叫。

  5. Form1_Load 事件處理常式結尾,新增 SetEnabled 的呼叫。

  6. 執行應用程式。 如果 ListBox 中未選取項目,則會停用 [儲存結果] 核取方塊和 [檢查] 按鈕。

使用 My.Computer.FileSystem 的完整範例

下列是完整範例。


' This example uses members of the My.Computer.FileSystem
' object, which are available in Visual Basic.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    ' Set the default directory of the folder browser to the current directory.
    FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory

    SetEnabled()
End Sub

Private Sub browseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browseButton.Click
    If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
        ' List files in the folder.
        ListFiles(FolderBrowserDialog1.SelectedPath)
    End If
    SetEnabled()
End Sub

Private Sub ListFiles(ByVal folderPath As String)
    filesListBox.Items.Clear()

    Dim fileNames = My.Computer.FileSystem.GetFiles(
        folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.txt")

    For Each fileName As String In fileNames
        filesListBox.Items.Add(fileName)
    Next
End Sub

Private Sub examineButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles examineButton.Click
    If filesListBox.SelectedItem Is Nothing Then
        MessageBox.Show("Please select a file.")
        Exit Sub
    End If

    ' Obtain the file path from the list box selection.
    Dim filePath = filesListBox.SelectedItem.ToString

    ' Verify that the file was not removed since the
    ' Browse button was clicked.
    If My.Computer.FileSystem.FileExists(filePath) = False Then
        MessageBox.Show("File Not Found: " & filePath)
        Exit Sub
    End If

    ' Obtain file information in a string.
    Dim fileInfoText As String = GetTextForOutput(filePath)

    ' Show the file information.
    MessageBox.Show(fileInfoText)

    If saveCheckBox.Checked = True Then
        ' Place the log file in the same folder as the examined file.
        Dim logFolder As String = My.Computer.FileSystem.GetFileInfo(filePath).DirectoryName
        Dim logFilePath = My.Computer.FileSystem.CombinePath(logFolder, "log.txt")

        Dim logText As String = "Logged: " & Date.Now.ToString &
            vbCrLf & fileInfoText & vbCrLf & vbCrLf

        ' Append text to the log file.
        My.Computer.FileSystem.WriteAllText(logFilePath, logText, append:=True)
    End If
End Sub

Private Function GetTextForOutput(ByVal filePath As String) As String
    ' Verify that the file exists.
    If My.Computer.FileSystem.FileExists(filePath) = False Then
        Throw New Exception("File Not Found: " & filePath)
    End If

    ' Create a new StringBuilder, which is used
    ' to efficiently build strings.
    Dim sb As New System.Text.StringBuilder()

    ' Obtain file information.
    Dim thisFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath)

    ' Add file attributes.
    sb.Append("File: " & thisFile.FullName)
    sb.Append(vbCrLf)
    sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
    sb.Append(vbCrLf)
    sb.Append("Size: " & thisFile.Length.ToString & " bytes")
    sb.Append(vbCrLf)

    ' Open the text file.
    Dim sr As System.IO.StreamReader =
        My.Computer.FileSystem.OpenTextFileReader(filePath)

    ' Add the first line from the file.
    If sr.Peek() >= 0 Then
        sb.Append("First Line: " & sr.ReadLine())
    End If
    sr.Close()

    Return sb.ToString
End Function

Private Sub filesListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filesListBox.SelectedIndexChanged
    SetEnabled()
End Sub

Private Sub SetEnabled()
    Dim anySelected As Boolean =
        (filesListBox.SelectedItem IsNot Nothing)

    examineButton.Enabled = anySelected
    saveCheckBox.Enabled = anySelected
End Sub

使用 System.IO 的完整範例

下列對等範例使用來自 System.IO 命名空間的類別,而不是使用 My.Computer.FileSystem 物件。


' This example uses classes from the System.IO namespace.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    ' Set the default directory of the folder browser to the current directory.
    FolderBrowserDialog1.SelectedPath =
        System.IO.Directory.GetCurrentDirectory()

    SetEnabled()
End Sub

Private Sub browseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browseButton.Click
    If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
        ' List files in the folder.
        ListFiles(FolderBrowserDialog1.SelectedPath)
        SetEnabled()
    End If
End Sub

Private Sub ListFiles(ByVal folderPath As String)
    filesListBox.Items.Clear()

    Dim fileNames As String() =
        System.IO.Directory.GetFiles(folderPath,
            "*.txt", System.IO.SearchOption.TopDirectoryOnly)

    For Each fileName As String In fileNames
        filesListBox.Items.Add(fileName)
    Next
End Sub

Private Sub examineButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles examineButton.Click
    If filesListBox.SelectedItem Is Nothing Then
        MessageBox.Show("Please select a file.")
        Exit Sub
    End If

    ' Obtain the file path from the list box selection.
    Dim filePath = filesListBox.SelectedItem.ToString

    ' Verify that the file was not removed since the
    ' Browse button was clicked.
    If System.IO.File.Exists(filePath) = False Then
        MessageBox.Show("File Not Found: " & filePath)
        Exit Sub
    End If

    ' Obtain file information in a string.
    Dim fileInfoText As String = GetTextForOutput(filePath)

    ' Show the file information.
    MessageBox.Show(fileInfoText)

    If saveCheckBox.Checked = True Then
        ' Place the log file in the same folder as the examined file.
        Dim logFolder As String =
            System.IO.Path.GetDirectoryName(filePath)
        Dim logFilePath = System.IO.Path.Combine(logFolder, "log.txt")

        ' Append text to the log file.
        Dim logText As String = "Logged: " & Date.Now.ToString &
            vbCrLf & fileInfoText & vbCrLf & vbCrLf

        System.IO.File.AppendAllText(logFilePath, logText)
    End If
End Sub

Private Function GetTextForOutput(ByVal filePath As String) As String
    ' Verify that the file exists.
    If System.IO.File.Exists(filePath) = False Then
        Throw New Exception("File Not Found: " & filePath)
    End If

    ' Create a new StringBuilder, which is used
    ' to efficiently build strings.
    Dim sb As New System.Text.StringBuilder()

    ' Obtain file information.
    Dim thisFile As New System.IO.FileInfo(filePath)

    ' Add file attributes.
    sb.Append("File: " & thisFile.FullName)
    sb.Append(vbCrLf)
    sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
    sb.Append(vbCrLf)
    sb.Append("Size: " & thisFile.Length.ToString & " bytes")
    sb.Append(vbCrLf)

    ' Open the text file.
    Dim sr As System.IO.StreamReader =
        System.IO.File.OpenText(filePath)

    ' Add the first line from the file.
    If sr.Peek() >= 0 Then
        sb.Append("First Line: " & sr.ReadLine())
    End If
    sr.Close()

    Return sb.ToString
End Function

Private Sub filesListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filesListBox.SelectedIndexChanged
    SetEnabled()
End Sub

Private Sub SetEnabled()
    Dim anySelected As Boolean =
        (filesListBox.SelectedItem IsNot Nothing)

    examineButton.Enabled = anySelected
    saveCheckBox.Enabled = anySelected
End Sub

另請參閱