チュートリアル : 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 フォーム アプリケーション] をクリックします。

  3. [名前] ボックスに「FileExplorer」と入力してプロジェクト名を設定し、[OK] をクリックします。

    Visual Studio のソリューション エクスプローラーにプロジェクトが追加され、Windows フォーム デザイナーが開きます。

  4. 次の表にあるコントロールをフォームに追加し、それらのプロパティに対応する値を設定します。

    コントロール プロパティ
    ListBox 名前 filesListBox
    Button 名前

    Text
    browseButton

    [参照]
    Button 名前

    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 呼び出しにより、[フォルダーの参照] ダイアログ ボックスが開きます。 ユーザーが [OK] をクリックすると、次の手順で追加する ListFiles メソッドに SelectedPath プロパティが引数として渡されます。

  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 ファイルが含まれているフォルダーを参照し、そのフォルダーを選択して [OK] をクリックします。

    ListBox に、選択したフォルダー内のファイルが追加されます。

  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 ファイルが含まれているフォルダーを参照します。 [OK] をクリックします。

    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 コントロールをダブルクリックして、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 を使用した完全な例

次に示す同等の例では、My.Computer.FileSystem オブジェクトではなく、System.IO 名前空間のクラスを使用しています。


' 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

関連項目