연습: Visual Basic에서 파일과 디렉터리 조작

업데이트: 2010년 12월

이 연습에서는 Visual Basic의 파일 I/O와 관련된 기본 사항을 소개합니다. 디렉터리의 텍스트 파일을 나열하고 검사하는 작은 응용 프로그램을 만드는 방법도 설명합니다. 응용 프로그램에서는 선택한 각 텍스트 파일에 대한 파일 특성과 파일 내용의 첫 번째 줄을 제공합니다. 로그 파일에 정보를 쓰는 옵션도 있습니다.

이 연습에서는 My.Computer.FileSystem Object의 멤버를 사용하며, 이 멤버는 Visual Basic에서 제공됩니다. 자세한 내용은 FileSystem을 참조하십시오. 연습의 마지막 부분에서는 System.IO 네임스페이스의 클래스를 사용하는 해당 예제를 제공합니다.

참고

다음 지침처럼 컴퓨터에서 Visual Studio 사용자 인터페이스 요소 일부에 대한 이름이나 위치를 다르게 표시할 수 있습니다. 이러한 요소는 사용하는 Visual Studio 버전 및 설정에 따라 결정됩니다. 자세한 내용은 Visual Studio 설정을 참조하십시오.

프로젝트를 만들려면

  1. 파일 메뉴에서 새 프로젝트를 클릭합니다.

    새 프로젝트 대화 상자가 나타납니다.

  2. 설치된 템플릿 창에서 Visual Basic을 확장한 다음 Windows를 클릭합니다. 가운데의 템플릿 창에서 Windows Forms 응용 프로그램을 클릭합니다.

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

    Visual Studio에서 솔루션 탐색기에 프로젝트가 추가되고 Windows Forms 디자이너가 열립니다.

  4. 다음 표에 나온 컨트롤을 폼에 추가하고 속성에 해당 값을 설정합니다.

    Control

    Property

    ListBox

    Name

    filesListBox

    Button

    Name

    Text

    browseButton

    Browse

    Button

    Name

    Text

    examineButton

    Examine

    CheckBox

    Name

    Text

    saveCheckBox

    Save Results

    FolderBrowserDialog

    Name

    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 파일이 들어 있는 폴더를 찾은 다음 폴더를 선택하고 확인을 클릭합니다.

    선택한 폴더에 있는 .txt 파일 목록이 ListBox에 포함됩니다.

  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
    

    SetEnabled 메서드는 ListBox에서 항목이 선택되어 있는지 여부에 따라 컨트롤을 사용하거나 사용하지 않도록 설정합니다.

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

  3. 새 filesListBox_SelectedIndexChanged 이벤트 처리기에서 SetEnabled에 대한 호출을 추가합니다.

  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를 사용하는 전체 예제

다음과 같은 예제에서는 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월

샘플 코드를 업데이트하고 수정했습니다.

고객 의견