Wskazówki: manipulowanie plikami i katalogami w Visual Basic

Ten instruktaż zawiera wprowadzenie do podstawy operacji We/Wy w Visual Basic.Opisuje sposób tworzenia małych aplikacji, która zawiera listę i analizuje pliki tekstowe w katalogu.Dla każdego pliku zaznaczonego tekstu aplikacja zawiera atrybuty plików i pierwszym wierszem zawartości.Istnieje możliwość zapisu informacji w pliku dziennika.

W tym instruktażu wykorzystano członków My.Computer.FileSystem Object, które są dostępne w Visual Basic.Zobacz FileSystem Aby uzyskać więcej informacji.Na końcu Instruktaż przykładem równoważne jest pod warunkiem że korzysta z klas z System.IO obszaru nazw.

[!UWAGA]

Na komputerze w poniższych instrukcjach mogą być wyświetlane inne nazwy i lokalizacje niektórych elementów interfejsu użytkownika programu Visual Studio. Te elementy są określane przez numer wersji Visual Studio oraz twoje ustawienia. Aby uzyskać więcej informacji, zobacz Dostosowywanie ustawień środowiska deweloperskiego w Visual Studio.

Aby utworzyć projekt

  1. Na pliku menu, kliknij przycisk Nowy projekt.

    Nowy projekt pojawi się okno dialogowe.

  2. W Zainstalowane szablony okienku rozwiń języka Visual Basic, a następnie kliknij przycisk Windows.W szablonów okienka, kliknij środkowy, Aplikacji Windows Forms.

  3. W Nazwa wpisz FileExplorer ustawić nazwę projektu, a następnie kliknij przycisk OK.

    Visual StudioProgram doda projekt do Solution Explorer, i zostanie otwarty projektant Windows Forms.

  4. Dodać formanty w poniższej tabeli przedstawiono w formularzu i ustaw odpowiednie wartości dla ich właściwości.

    Kontrola

    Właściwość

    Wartość

    Pole listy

    Nazwa

    filesListBox

    Przycisk

    Nazwa

    Tekst

    browseButton

    Przeglądaj

    Przycisk

    Nazwa

    Tekst

    examineButton

    Zbadać

    Pole wyboru

    Nazwa

    Tekst

    saveCheckBox

    Zapisz wyniki

    Dialogowym FolderBrowserDialog

    Nazwa

    FolderBrowserDialog1

Wybierz folder oraz wyświetlanie listy plików w folderze

  1. Tworzenie Click obsługi zdarzenia browseButton przez dwukrotne kliknięcie formantu w formularzu.Otwiera edytor kodu.

  2. Dodaj następujący kod do Click programu obsługi zdarzeń.

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

    FolderBrowserDialog1.ShowDialog Wywołania otwiera Przeglądanie w poszukiwaniu folderu okno dialogowe.Gdy użytkownik kliknie OK, SelectedPath właściwość jest wysyłany jako argument do ListFiles metodę, która jest dodawana w następnym kroku.

  3. Dodaje się ListFiles metody.

    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
    

    Ten kod najpierw czyści ListBox.

    GetFiles Metoda pobiera następnie Kolekcja ciągów, jeden dla każdego pliku w katalogu.GetFiles Metoda przyjmuje argument wzorzec wyszukiwania do pobierania plików, które pasuje do określonego wzorca.W tym przykładzie zwracane są tylko te pliki, które mają rozszerzenie .txt.

    Ciągi, które są zwracane przez GetFiles metoda zostają następnie dodane do ListBox.

  4. Uruchom aplikację.Kliknij przycisk przeglądać przycisku.W Przeglądanie w poszukiwaniu folderu okno dialogowe Przejdź do folderu, który zawiera pliki .txt, a następnie wybierz folder i kliknij przycisk OK.

    ListBox Zawiera listę plików .txt w wybranym folderze.

  5. Zatrzymaj z uruchomioną aplikacją.

Aby uzyskać atrybuty pliku i zawartości z pliku tekstowego

  1. Tworzenie Click obsługi zdarzenia examineButton przez dwukrotne kliknięcie formantu w formularzu.

  2. Dodaj następujący kod do Click programu obsługi zdarzeń.

    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)
    

    Kod sprawdza, czy element jest zaznaczony w ListBox.Następnie uzyska wpis ścieżki pliku z ListBox.FileExists Metoda jest używana do sprawdzania, czy plik nadal istnieje.

    Ścieżka pliku jest wysyłana jako argument do GetTextForOutput metodę, która jest dodawana w następnym kroku.Ta metoda zwraca ciąg zawierający informacje o pliku.Informacje o pliku pojawia się w MessageBox.

  3. Dodaje się GetTextForOutput metody.

    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
    

    W kodzie wykorzystano GetFileInfo metoda uzyskania parametry pliku.Parametry pliku są dodawane do StringBuilder.

    OpenTextFileReader Metoda odczytuje zawartość pliku do StreamReader.Pierwszy wiersz zawartość jest uzyskiwany z StreamReader i dodaje się do StringBuilder.

  4. Uruchom aplikację.Kliknij przycisk przeglądać, a następnie przejdź do folderu zawierającego pliki z rozszerzeniem .txt.Click OK.

    Wybierz plik w ListBox, a następnie kliknij przycisk Zbadaj.A MessageBox zawiera informacje o pliku.

  5. Zatrzymaj z uruchomioną aplikacją.

Aby dodać wpis dziennika

  1. Dodaj następujący kod do końca examineButton_Click programu obsługi zdarzeń.

    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
    

    Kod ustawia ścieżkę pliku dziennika, aby umieścić plik dziennika w tym samym katalogu co wybrany plik.Tekst wpis dziennika jest ustawiony do bieżącej daty i czasu następuje informacje o pliku.

    WriteAllText Metodę, z append ustawić argument True, jest używany do tworzenia wpisu dziennika.

  2. Uruchom aplikację.Przejdź do pliku tekstowego, zaznacz go w ListBox, wybierz opcję Zapisać wyniki pole wyboru, a następnie kliknij przycisk Zbadaj.Sprawdź, że wpis dziennika jest zapisywane w log.txt pliku.

  3. Zatrzymaj z uruchomioną aplikacją.

Aby użyć bieżącego katalogu.

  1. Utwórz moduł obsługi zdarzenia Form1_Load przez dwukrotne kliknięcie formularza.

  2. Dodaj następujący kod do obsługi zdarzenia.

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

    Ten kod ustawia domyślny katalog przeglądarka folderu do bieżącego katalogu.

  3. Uruchom aplikację.Po kliknięciu przycisku przeglądać po raz pierwszy Przeglądanie w poszukiwaniu folderu w bieżącym katalogu zostanie otwarte okno dialogowe.

  4. Zatrzymaj z uruchomioną aplikacją.

Do selektywnego włączania formantów

  1. Dodaje się SetEnabled metody.

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

    SetEnabled Metoda włącza lub wyłącza formanty w zależności od tego, czy element jest zaznaczony w ListBox.

  2. Tworzenie SelectedIndexChanged obsługi zdarzenia filesListBox przez dwukrotne kliknięcie ListBox formantu w formularzu.

  3. Dodać wywołanie SetEnabled w nowym filesListBox_SelectedIndexChanged programu obsługi zdarzeń.

  4. Dodać wywołanie SetEnabled na końcu browseButton_Click programu obsługi zdarzeń.

  5. Dodać wywołanie SetEnabled na końcu Form1_Load programu obsługi zdarzeń.

  6. Uruchom aplikację.Zapisać wyniki pole wyboru i Zbadaj przycisk są wyłączone, jeśli nie zostanie zaznaczony element w ListBox.

Pełny przykład przy użyciu My.Computer.FileSystem

Oto przykład pełną.

    ' 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

Pełny przykład using System.IO

W poniższym przykładzie równoważne użyto klasy z System.IO nazw zamiast My.Computer.FileSystem obiektów.

' 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

Zobacz też

Zadania

Wskazówki: manipulowanie plikami za pomocą metod .NET Framework (Visual Basic)

Informacje

System.IO

FileSystem

CurrentDirectory