共用方式為


逐步解說:在 Visual Basic 中操作與管理檔案及目錄

本逐步解說提供 Visual Basic 中檔案 I/O 的基本概念簡介。 這裡描述了建立一個能列出和檢查目錄中文本檔的小型應用程式的過程。 針對每個選取的文字檔,應用程式會提供檔案屬性和第一行內容。 有一個選項可將資訊寫入記錄檔。

本逐步解說會使用 Visual Basic 中的 My.Computer.FileSystem Object 成員。 如需相關資訊,請參閱 FileSystem 。 在逐步解說結束時,會提供一個使用System.IO命名空間中的類別的相應範例。

備註

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

建立專案

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

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

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

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

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

  4. 將下表中的控件新增至窗體,並設定其屬性的對應值。

    管理 房產 價值觀
    ListBox 名稱 filesListBox
    按鈕 名稱

    文字
    browseButton

    瀏覽
    按鈕 名稱

    文字
    examineButton

    檢查
    核取方塊 名稱

    文字
    saveCheckBox

    儲存結果
    FolderBrowserDialog 名稱 FolderBrowserDialog1

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

  1. 在表單上的控制項上按兩下以建立Click事件處理程式browseButton。 [程式代碼編輯器] 隨即開啟。

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

  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
    

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

    使用 WriteAllText 方法將參數 append 設定為 True,用來建立日誌條目。

  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. 在表單上按兩下SelectedIndexChanged控制件,以建立filesListBoxListBox事件處理程式。

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

  4. SetEnabled 事件處理程式結尾新增呼叫 browseButton_Click

  5. SetEnabled 事件處理程式結尾新增呼叫 Form1_Load

  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

另請參閱