次の方法で共有


チュートリアル: 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
    ボタン 名前

    テキスト
    browseButton

    ブラウズ
    ボタン 名前

    テキスト
    examineButton

    尋問する
    のチェックボックスを にする 名前

    テキスト
    saveCheckBox

    結果を保存する
    FolderBrowserDialog 名前 FolderBrowserDialog1

フォルダーを選択し、フォルダー内のファイルを一覧表示するには

  1. フォーム上のコントロールをダブルクリックして、ClickbrowseButton イベント ハンドラーを作成します。 コード エディターが開きます。

  2. Click イベント ハンドラーに次のコードを追加します。

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

    FolderBrowserDialog1.ShowDialog呼び出しで、[フォルダーの参照] ダイアログ ボックスが開きます。 ユーザーが [OK] をクリックすると、 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 メソッドは、ディレクトリ内のファイルごとに 1 つずつ、文字列のコレクションを取得します。 GetFiles メソッドは、特定のパターンに一致するファイルを取得する検索パターン引数を受け取ります。 この例では、拡張子が .txt ファイルのみが返されます。

    その後、 GetFiles メソッドによって返される文字列が ListBox に追加されます。

  4. アプリケーションを実行します。 [ 参照 ] ボタンをクリックします。 [ フォルダーの参照 ] ダイアログ ボックスで、.txt ファイルを含むフォルダーを参照し、フォルダーを選択して [ OK] をクリックします。

    ListBoxには、選択したフォルダー内の .txt ファイルの一覧が含まれています。

  5. アプリケーションの実行を停止します。

ファイルの属性とテキスト ファイルからコンテンツを取得するには

  1. フォーム上のコントロールをダブルクリックして、ClickexamineButton イベント ハンドラーを作成します。

  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 メソッドに引数として送信されます。 このメソッドは、ファイル情報を含む文字列を返します。 ファイル情報が メッセージ ボックスに表示されます。

  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
    

    このコードは、選択したファイルと同じディレクトリにログ ファイルを配置するようにログ ファイルのパスを設定します。 ログ エントリのテキストは、現在の日時に設定され、その後にファイル情報が続きます。

    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

こちらも参照ください