チュートリアル : Visual Basic によるファイルとディレクトリの操作

更新 : 2010 年 12 月

このチュートリアルでは、Visual Basic によるファイル I/O の基本事項について紹介します。 ここでは、ディレクトリ内のテキスト ファイルを一覧表示し、ファイルの内容をチェックする小さなアプリケーションを作成する方法について説明します。 このアプリケーションでは、選択した各テキスト ファイルのファイル属性と内容の 1 行目を表示します。 また、情報をログ ファイルに書き込むオプションもあります。

このチュートリアルでは、Visual Basic で提供される My.Computer.FileSystem Object のメンバーを使用します。 詳細については、「FileSystem」を参照してください。 このチュートリアルの最後に、System.IO 名前空間のクラスを使用した場合の同等のコード例を示します。

注意

お使いのマシンで、Visual Studio ユーザー インターフェイスの一部の要素の名前や場所が、次の手順とは異なる場合があります。 これらの要素は、使用している Visual Studio のエディションや独自の設定によって決まります。 詳細については、「Visual Studio の設定」を参照してください。

プロジェクトを作成するには

  1. [ファイル] メニューの [新しいプロジェクト] をクリックします。

    [新しいプロジェクト] ダイアログ ボックスが表示されます。

  2. [インストールされたテンプレート] ペインで、[Visual Basic] を展開し、[Windows] をクリックします。 中央の [テンプレート] ペインで、[Windows フォーム アプリケーション] をクリックします。

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

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

  4. 次の表に示すコントロールをフォームに追加し、プロパティの値を設定します。

    コントロール

    プロパティ

    ListBox

    [名前]

    filesListBox

    Button

    [名前]

    Text

    browseButton

    Browse

    Button

    [名前]

    Text

    examineButton

    Examine

    CheckBox

    [名前]

    Text

    saveCheckBox

    Save Results

    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 の呼び出しによって、[フォルダーの参照] ダイアログ ボックスが開きます。 ユーザーが [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. アプリケーションを実行します。 [Browse] をクリックします。 [フォルダーの参照] ダイアログ ボックスで、.txt ファイルが格納されたフォルダーを参照し、そのフォルダーを選択して [OK] をクリックします。

    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 からファイルの内容の 1 行目が取得され、StringBuilder に追加されます。

  4. アプリケーションを実行します。 [Browse] をクリックし、.txt ファイルが格納されたフォルダーを参照します。 [OK] をクリックします。

    ListBox でファイルを選択し、[Examine] をクリックします。 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 でファイルを選択します。[Save Results] チェック ボックスをオンにし、[Examine] をクリックします。 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. アプリケーションを実行します。 [Browse] をクリックすると、[フォルダーの参照] ダイアログ ボックスが開き、現在のディレクトリが表示されます。

  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 で項目が選択されていない場合、[Save Results] チェック ボックスと [Examine] ボタンが無効になります。

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

参照

処理手順

チュートリアル: .NET Framework のメソッドによるファイル操作 (Visual Basic)

参照

System.IO

FileSystem

CurrentDirectory

履歴の変更

日付

履歴

理由

2010 年 12 月

例とチュートリアルが変更されました。

内容の充実

2010 年 8 月

サンプル コードが更新および修正されました。

カスタマー フィードバック