이 연습에서는 Visual Basic에서 파일 I/O의 기본 사항을 소개합니다. 디렉터리의 텍스트 파일을 나열하고 검사하는 작은 애플리케이션을 만드는 방법을 설명합니다. 선택한 각 텍스트 파일에 대해 애플리케이션은 파일 특성과 첫 번째 콘텐츠 줄을 제공합니다. 로그 파일에 정보를 쓰는 옵션이 있습니다.
이 연습에서는 My.Computer.FileSystem Object
의 멤버를 사용하며, 이는 Visual Basic에서 사용할 수 있습니다. 자세한 내용은 FileSystem을 참조하세요. 단계별 안내의 끝에서는 System.IO 네임스페이스의 클래스를 사용하는 동일한 예를 제공합니다.
비고
컴퓨터는 다음 지침에서 Visual Studio 사용자 인터페이스 요소 중 일부에 대해 다른 이름 또는 위치를 표시할 수 있습니다. 가지고 있는 Visual Studio 버전과 사용하는 설정에 따라 이러한 요소가 결정됩니다. 자세한 내용은 IDE 개인 설정참조하세요.
프로젝트를 만들려면
파일 메뉴에서 새 프로젝트를 클릭합니다.
새 프로젝트 대화 상자가 나타납니다.
설치된 템플릿 창에서 Visual Basic을 확장한 다음 Windows를 클릭합니다. 가운데에 있는 템플릿 창에서 Windows Forms 애플리케이션을 클릭합니다.
이름 상자에 프로젝트 이름을 설정하려면 입력
FileExplorer
하고 확인을 클릭합니다.Visual Studio는 솔루션 탐색기에 프로젝트를 추가하고 Windows Forms 디자이너가 열립니다.
다음 표의 컨트롤을 폼에 추가하고 해당 속성에 해당하는 값을 설정합니다.
제어 재산 가치 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
폴더 찾아보기 대화 상자가 열립니다. 사용자가 확인을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 디렉터리의 각 파일에 대해 하나씩 문자열 컬렉션을 검색합니다. 메서드는
GetFiles
특정 패턴과 일치하는 파일을 검색하기 위해 검색 패턴 인수를 허용합니다. 이 예제에서는 확장명이 .txt 파일만 반환됩니다.그런 다음 메서드에서 반환
GetFiles
되는 문자열이 ListBox에 추가됩니다.애플리케이션을 실행합니다. 찾아보기 버튼을 클릭합니다. 폴더 찾아보기 대화 상자에서 .txt 파일이 포함된 폴더로 이동한 다음 폴더를 선택하고 확인을 클릭합니다.
선택한
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
대한 인수로 전송됩니다. 이 메서드는 파일 정보를 포함하는 문자열을 반환합니다. 파일 정보가 MessageBox에 나타납니다.다음 메서드를 추가합니다
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
파일을 선택한 다음 검사를 클릭합니다. AMessageBox
는 파일 정보를 표시합니다.애플리케이션 실행을 중지합니다.
로그 항목을 추가하려면
이벤트 처리기의 끝에
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
호출을 추가합니다.이벤트 처리기의 끝에
SetEnabled
호출을 추가합니다.애플리케이션을 실행합니다. 에서 항목을 선택하지 않으면 결과 저장 확인란과
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