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

這個逐步解說將介紹 Visual Basic 中 I/O 檔案的基本原則。 它將說明如何建立一個小型應用程式,此應用程式會列出並檢查目錄中的文字檔。 這個應用程式會為每個選取的文字檔,提供檔案屬性及第一行內容。 還有一個將資訊寫入記錄檔的選項。

本逐步解說會使用 My.Computer.FileSystem Object 的成員,這些成員可從 Visual Basic 取得。 如需詳細資訊,請參閱 FileSystem。 在本逐步解說的最後,將提供同等的範例,它會使用來自 System.IO 命名空間的類別。

注意事項注意事項

您的電腦對於下列指示中某些 Visual Studio 使用者介面項目的名稱或位置,可能會顯示不同的資訊:您所擁有的 Visual Studio 版本以及使用的設定會決定這些項目。如需詳細資訊,請參閱<Visual Studio 中的自訂開發設定>。

若要建立專案

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

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

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

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

    Visual Studio 會將專案加入 [方案總管] 中,並開啟 Windows Form 設計工具。

  4. 將下表中的控制項加入表單,並設定控制項屬性的對應值。

    控制項

    屬性

    ListBox

    名稱

    filesListBox

    Button

    名稱

    文字

    browseButton

    瀏覽

    Button

    名稱

    文字

    examineButton

    檢查

    CheckBox

    名稱

    文字

    saveCheckBox

    儲存結果

    FolderBrowserDialog

    名稱

    FolderBrowserDialog1

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

  1. 按兩下表單上的控制項來建立 browseButton 的 Click 事件處理常式。 程式碼編輯器立即開啟。

  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. 按兩下表單上的控制項來建立 examineButton 的 Click 事件處理常式。

  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 引數設為 True 的 WriteAllText 方法是用來建立記錄項目。

  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 控制項來建立 filesListBox 的 SelectedIndexChanged 事件處理常式。

  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

請參閱

工作

逐步解說:使用 .NET Framework 方法管理檔案 (Visual Basic)

參考

System.IO

FileSystem

CurrentDirectory