このチュートリアルでは、Visual Basic でのファイル I/O の基礎について説明します。 ディレクトリ内のテキスト ファイルを一覧表示して調べる小さなアプリケーションを作成する方法について説明します。 選択したテキスト ファイルごとに、アプリケーションはファイル属性とコンテンツの最初の行を提供します。 ログ ファイルに情報を書き込むオプションがあります。
このチュートリアルでは、Visual Basic で使用できる My.Computer.FileSystem Object
のメンバーを使用します。 詳細については、FileSystem を参照してください。 チュートリアルの最後には、 System.IO 名前空間のクラスを使用する同等の例が用意されています。
注
次の手順では、一部の Visual Studio ユーザー インターフェイス要素の名前や場所がコンピューターに異なる場合があります。 これらの要素は、使用している Visual Studio エディションと使用する設定によって決まります。 詳細については、「IDEのカスタマイズ」を参照してください。
プロジェクトを作成するには
[ ファイル ] メニューの [ 新しいプロジェクト] をクリックします。
[新しいプロジェクト] ダイアログ ボックスが表示されます。
[インストールされているテンプレート] ウィンドウで、[Visual Basic] を展開し、[Windows] をクリックします。 中央の [ テンプレート ] ウィンドウで、[ Windows フォーム アプリケーション] をクリックします。
[ 名前 ] ボックスに「
FileExplorer
」と入力してプロジェクト名を設定し、[OK] をクリック します。Visual Studio によって ソリューション エクスプローラーにプロジェクトが追加され、Windows フォーム デザイナーが開きます。
次の表のコントロールをフォームに追加し、そのプロパティに対応する値を設定します。
コントロール プロパティ 価値 の ListBox 名前 filesListBox
ボタン 名前
テキストbrowseButton
ブラウズボタン 名前
テキストexamineButton
尋問するのチェックボックスを にする 名前
テキストsaveCheckBox
結果を保存するFolderBrowserDialog 名前 FolderBrowserDialog1
フォルダーを選択し、フォルダー内のファイルを一覧表示するには
フォーム上のコントロールをダブルクリックして、
Click
のbrowseButton
イベント ハンドラーを作成します。 コード エディターが開きます。Click
イベント ハンドラーに次のコードを追加します。If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then ' List files in the folder. ListFiles(FolderBrowserDialog1.SelectedPath) End If
FolderBrowserDialog1.ShowDialog
呼び出しで、[フォルダーの参照] ダイアログ ボックスが開きます。 ユーザーが [OK] をクリックすると、 SelectedPath プロパティが引数としてListFiles
メソッドに送信されます。これは次の手順で追加されます。次の
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 に追加されます。アプリケーションを実行します。 [ 参照 ] ボタンをクリックします。 [ フォルダーの参照 ] ダイアログ ボックスで、.txt ファイルを含むフォルダーを参照し、フォルダーを選択して [ OK] をクリックします。
ListBox
には、選択したフォルダー内の .txt ファイルの一覧が含まれています。アプリケーションの実行を停止します。
ファイルの属性とテキスト ファイルからコンテンツを取得するには
フォーム上のコントロールをダブルクリックして、
Click
の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)
コードは、
ListBox
で項目が選択されていることを確認します。 次に、ListBox
からファイル パス エントリを取得します。 FileExistsメソッドは、ファイルがまだ存在するかどうかを確認するために使用されます。ファイル パスは、次の手順で追加される
GetTextForOutput
メソッドに引数として送信されます。 このメソッドは、ファイル情報を含む文字列を返します。 ファイル情報が メッセージ ボックスに表示されます。次の
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
に追加されます。アプリケーションを実行します。 [ 参照] をクリックし、.txt ファイルを含むフォルダーを参照します。 OK をクリックします。
ListBox
でファイルを選択し、[確認] をクリックします。MessageBox
にファイル情報が表示されます。アプリケーションの実行を停止します。
ログ エントリを追加するには
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
メソッドを使用して、ログ エントリを作成します。アプリケーションを実行します。 テキスト ファイルを参照し、
ListBox
で選択し、[ 結果の保存 ] チェック ボックスをオンにして、[ 確認] をクリックします。 ログ エントリがlog.txt
ファイルに書き込まれたことを確認します。アプリケーションの実行を停止します。
現在のディレクトリを使用するには
フォームをダブルクリックして、
Form1_Load
のイベント ハンドラーを作成します。イベント ハンドラーに次のコードを追加します。
' Set the default directory of the folder browser to the current directory. FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory
このコードは、フォルダー ブラウザーの既定のディレクトリを現在のディレクトリに設定します。
アプリケーションを実行します。 [初めて 参照 ] をクリックすると、[ フォルダーの参照 ] ダイアログ ボックスが開き、現在のディレクトリが表示されます。
アプリケーションの実行を停止します。
コントロールを選択的に有効にするには
次の
SetEnabled
メソッドを追加します。Private Sub SetEnabled() Dim anySelected As Boolean = (filesListBox.SelectedItem IsNot Nothing) examineButton.Enabled = anySelected saveCheckBox.Enabled = anySelected End Sub
SetEnabled
メソッドは、ListBox
で項目が選択されているかどうかに応じてコントロールを有効または無効にします。フォームの
SelectedIndexChanged
コントロールをダブルクリックして、filesListBox
のListBox
イベント ハンドラーを作成します。新しい
SetEnabled
イベント ハンドラーでfilesListBox_SelectedIndexChanged
の呼び出しを追加します。SetEnabled
イベント ハンドラーの末尾にbrowseButton_Click
の呼び出しを追加します。SetEnabled
イベント ハンドラーの末尾にForm1_Load
の呼び出しを追加します。アプリケーションを実行します。 で項目が選択されていない場合、[結果の保存] チェック ボックスと [
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
こちらも参照ください
.NET