다음을 통해 공유


연습: 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 Forms 애플리케이션을 클릭합니다.

  3. 이름 상자에 FileExplorer를 입력하여 프로젝트 이름을 설정한 다음 확인을 클릭합니다.

    Visual Studio에서 솔루션 탐색기에 프로젝트를 추가합니다. 그러면 Windows Forms 디자이너가 열립니다.

  4. 다음 표의 컨트롤을 양식에 추가하고 속성의 해당 값을 설정합니다.

    제어 속성
    ListBox 이름 filesListBox
    단추 이름

    Text
    browseButton

    찾아보기
    단추 이름

    Text
    examineButton

    검사
    CheckBox 이름

    Text
    saveCheckBox

    결과 저장
    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 호출은 폴더 찾아보기 대화 상자를 엽니다. 사용자가 확인을 클릭하면 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 메서드는 디렉터리에 있는 각 파일에 대해 나하씩 문자열 컬렉션을 검색합니다. GetFiles 메서드는 특정 패턴과 일치하는 파일을 검색하기 위해 패턴 인수를 허용합니다. 이 예제에서는 확장명이 .txt인 파일만 반환됩니다.

    GetFiles 메서드에 의해 반환되는 문자열은 ListBox에 추가됩니다.

  4. 애플리케이션을 실행합니다. 찾아보기 단추를 클릭합니다. 폴더 찾아보기 대화 상자에서 .txt 파일이 있는 폴더로 이동하여 폴더를 선택하고 확인을 클릭합니다.

    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에서 가져와 StringBuilder에 추가합니다.

  4. 애플리케이션을 실행합니다. 찾아보기를 클릭하고 .txt 파일이 포함된 폴더로 이동합니다. 확인을 클릭합니다.

    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
    

    ListBox에서 항목이 선택되었는지에 따라 SetEnabled 메서드는 컨트롤의 사용 여부를 설정합니다.

  2. 양식의 ListBox 컨트롤을 두 번 클릭하여 filesListBox에 대한 SelectedIndexChanged 이벤트 처리기를 만듭니다.

  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

참고 항목