VB.NET_기본 입출력

2015. 8. 4. 11:33Programming/VB.NET

파일 입/출력(I/O) 작업 예제
본 문서에 수록된 예제에서는 기본 파일 입/출력(I/O) 작업에 대해 설명합니다. 단계별 예제 절에서는 아래의 여섯 가지 파일 입/출력(I/O) 작업을 보여주는 간단한 응용 프로그램을 만드는 방법에 대해 설명합니다.

? 텍스트 파일 읽기
? 텍스트 파일 쓰기
? 파일 정보 보기
? 디스크 드라이브 나열
? 하위 폴더 나열
? 파일 나열


텍스트 파일 읽기
이 코드 예제에서는 StreamReader 클래스를 사용하여 System.ini 파일을 읽습니다. 파일 내용은 ListBox 컨트롤에 추가됩니다. try...catch 블록은 파일이 비어 있을 경우 프로그램에 경고를 보내는 데 사용됩니다. 파일 끝에 도달하는 시기를 결정하는 방법에는 여러 가지가 있지만, 이 예제에서는 Peek 메서드를 사용하여 파일을 읽기 전에 다음 줄을 검사합니다.
Dim reader As StreamReader = New StreamReader(winDir & "\system.ini")
    Try
        Me.ListBox1.Items.Clear()
        Do
            Me.ListBox1.Items.Add(reader.ReadLine)
        Loop Until reader.Peek = -1

    Catch
        Me.ListBox1.Items.Add("File is empty")

    Finally
        reader.Close()
    End Try


텍스트 파일 쓰기
이 코드 예제에서는 StreamWriter 클래스를 사용하여 파일을 만들고 파일 내용을 씁니다. 기존의 파일도 같은 방법으로 열 수 있습니다.
    Dim writer As StreamWriter = _
    New StreamWriter("c:\KBTest.txt")
    writer.WriteLine("File created using StreamWriter class.")
    writer.Close()


파일 정보 보기
이 코드 예제에서는 FileInfo 개체를 사용하여 파일 속성에 액세스합니다. 이 예제에서는 Notepad.exe가 사용됩니다. 파일 속성은 ListBox 컨트롤에 표시됩니다.
    Dim FileProps As FileInfo = New FileInfo(winDir & "\notepad.exe")
    With Me.ListBox1.Items
        .Clear()
        .Add("File Name = " & FileProps.FullName)
        .Add("Creation Time = " & FileProps.CreationTime)
        .Add("Last Access Time = " & FileProps.LastAccessTime)
        .Add("Last Write Time = " & FileProps.LastWriteTime)
        .Add("Size = " & FileProps.Length)
    End With
    FileProps = Nothing
디스크 드라이브 나열
이 코드 예제에서는 Directory와 Drive 클래스를 사용하여 시스템 상의 논리 드라이브를 나열합니다. 드라이브 목록은 ListBox 컨트롤에 표시됩니다.
    Dim dirInfo As Directory
    Dim drive As String
    Me.ListBox1.Items.Clear()
    Dim drives() As String = dirInfo.GetLogicalDrives()
    For Each drive In drives
        Me.ListBox1.Items.Add(drive)
    Next


하위 폴더 나열
이 코드 예제에서는 Directory 클래스의 GetDirectories 메서드를 사용하여 폴더 목록을 가져옵니다.
    Dim dir As String
    Me.ListBox1.Items.Clear()
    Dim dirs() As String = Directory.GetDirectories(winDir)
    For Each dir In dirs
        Me.ListBox1.Items.Add(dir)
    Next
파일 나열
이 코드 예제에서는 Directory 클래스의 GetFiles 메서드를 사용하여 파일 목록을 가져옵니다.
    Dim file As String
    Me.ListBox1.Items.Clear()
    Dim files() As String = Directory.GetFiles(winDir)
    For Each file In files
        Me.ListBox1.Items.Add(file)
    Next
사용자가 파일에 액세스할 때는 여러 가지 예외가 발생할 수 있습니다. 예를 들어, 파일이 없거나 파일이 이미 사용되고 있거나 액세스하려는 폴더의 파일에 대한 사용 권한이 없을 수 있습니다. 코드를 작성할 때는 이러한 가능성을 충분히 고려해서 생성되는 예외를 처리해야 합니다.


 위로 가기

단계별 예제
예제 빌드
1. Visual Basic .NET에서 새 Windows 응용 프로그램을 시작합니다. 기본적으로 Form1이 생성됩니다.
2. Form1 코드 창을 엽니다.
3. 코드 숨김 편집기에서 코드를 모두 삭제합니다.
4. 코드 숨김 편집기 창에 다음 코드를 붙여넣습니다.
Option Strict On
Imports System.IO

Public Class Form1
    Inherits System.Windows.Forms.Form
    Private winDir As String
#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call.

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub
                        Friend WithEvents ListBox1 As System.Windows.Forms.ListBox
    Friend WithEvents Button3 As System.Windows.Forms.Button
    Friend WithEvents Button5 As System.Windows.Forms.Button
    Friend WithEvents Button4 As System.Windows.Forms.Button
    Friend WithEvents Button2 As System.Windows.Forms.Button
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents Button6 As System.Windows.Forms.Button
   
    'This call is required by the Windows Form Designer.
    Private components As System.ComponentModel.Container

    'NOTE: The following procedure is required by the Windows Form Designer.
    'You can use the Windows Form Designer to modify it; however, do not
    'use the Code Editor to modify it.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.Button2 = New System.Windows.Forms.Button()
        Me.Button3 = New System.Windows.Forms.Button()
        Me.ListBox1 = New System.Windows.Forms.ListBox()
        Me.Button4 = New System.Windows.Forms.Button()
        Me.Button5 = New System.Windows.Forms.Button()
        Me.Button1 = New System.Windows.Forms.Button()
        Me.Button6 = New System.Windows.Forms.Button()
        Me.SuspendLayout()
        '
        'Button2
        '
        Me.Button2.Location = New System.Drawing.Point(272, 64)
        Me.Button2.Name = "Button2"
        Me.Button2.Size = New System.Drawing.Size(136, 23)
        Me.Button2.TabIndex = 1
        Me.Button2.Text = "Button2"
        '
        'Button3
        '
        Me.Button3.Location = New System.Drawing.Point(272, 96)
        Me.Button3.Name = "Button3"
        Me.Button3.Size = New System.Drawing.Size(136, 23)
        Me.Button3.TabIndex = 2
        Me.Button3.Text = "Button3"
        '
        'ListBox1
        '
        Me.ListBox1.Location = New System.Drawing.Point(16, 16)
        Me.ListBox1.Name = "ListBox1"
        Me.ListBox1.Size = New System.Drawing.Size(240, 238)
        Me.ListBox1.TabIndex = 5
        '
        'Button4
        '
        Me.Button4.Location = New System.Drawing.Point(272, 128)
        Me.Button4.Name = "Button4"
        Me.Button4.Size = New System.Drawing.Size(136, 23)
        Me.Button4.TabIndex = 3
        Me.Button4.Text = "Button4"
        '
        'Button5
        '
        Me.Button5.Location = New System.Drawing.Point(272, 160)
        Me.Button5.Name = "Button5"
        Me.Button5.Size = New System.Drawing.Size(136, 23)
        Me.Button5.TabIndex = 4
        Me.Button5.Text = "Button5"
        '
        'Button1
        '
        Me.Button1.Location = New System.Drawing.Point(272, 32)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(136, 23)
        Me.Button1.TabIndex = 0
        Me.Button1.Text = "Button1"
        '
        'Button6
        '
        Me.Button6.Location = New System.Drawing.Point(272, 192)
        Me.Button6.Name = "Button6"
        Me.Button6.Size = New System.Drawing.Size(136, 23)
        Me.Button6.TabIndex = 6
        Me.Button6.Text = "Button6"
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(416, 341)
        Me.Controls.AddRange(New System.Windows.Forms.Control() _
           {Me.Button6, Me.ListBox1, Me.Button5, Me.Button4, _
           Me.Button3, Me.Button2, Me.Button1})
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
      Handles MyBase.Load
        Me.Button1.Text = "Read Text File"
        Me.Button2.Text = "Write Text File"
        Me.Button3.Text = "View File Information"
        Me.Button4.Text = "List Drives"
        Me.Button5.Text = "List Subfolders"
        Me.Button6.Text = "List Files"
        winDir = System.Environment.GetEnvironmentVariable("windir")
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
      Handles Button1.Click
        'Demonstrates how to read a file by using StreamReader
        'Uses System.ini as an example
        'try...catch is used to detect a 0 byte file
        Dim reader As StreamReader = New StreamReader(winDir & "\system.ini")
       
  Try
            Me.ListBox1.Items.Clear()
            Do 'Until reader.Peek = -1
                Me.ListBox1.Items.Add(reader.ReadLine)
            Loop Until reader.Peek = -1

        Catch
            Me.ListBox1.Items.Add("File is empty")

        Finally
            reader.Close()
        End Try

    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
      Handles Button4.Click
        'Demonstrates how to obtain a list of disk drives
        Dim dirInfo As Directory
        Dim drive As String
        Me.ListBox1.Items.Clear()
        Dim drives() As String = dirInfo.GetLogicalDrives()
        For Each drive In drives
            Me.ListBox1.Items.Add(drive)
        Next
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
      Handles Button3.Click
        'Demonstrates how to access file properties. You can access folder properties
        'in the same way. More properties are available through the FileInfo class
        'than are demonstrated here.
        'You can also use the Directory class to obtain this information.
        Dim FileProps As FileInfo = New FileInfo(winDir & "\notepad.exe")
        With Me.ListBox1.Items
            .Clear()
            .Add("File Name = " & FileProps.FullName)
            .Add("Creation Time = " & FileProps.CreationTime)
            .Add("Last Access Time = " & FileProps.LastAccessTime)
            .Add("Last Write TIme = " & FileProps.LastWriteTime)
            .Add("Size = " & FileProps.Length)
        End With
        FileProps = Nothing
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
      Handles Button2.Click
        'Demonstrates how to create and write to a text file
        Dim writer As StreamWriter = _
            New StreamWriter("c:\KBTest.txt")
        writer.WriteLine("File created using StreamWriter class.")
        writer.Close()
        Me.ListBox1.Items.Clear()
        Me.ListBox1.Items.Add("File Written to C:\KBTest.txt")
    End Sub

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
      Handles Button5.Click
        'Demonstrates how to get a list of folders (example uses Windows folder)
        Dim dir As String
        Me.ListBox1.Items.Clear()
        Dim dirs() As String = Directory.GetDirectories(winDir)
        For Each dir In dirs
            Me.ListBox1.Items.Add(dir)
        Next
    End Sub

    Private Sub Button6_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
      Handles Button6.Click
        'Demonstrates how to get a list of files (example uses Windows folder)
        Dim file As String
        Me.ListBox1.Items.Clear()
        Dim files() As String = Directory.GetFiles(winDir)
        For Each file In files
            Me.ListBox1.Items.Add(file)
        Next
    End Sub
End Class
 

 

'Programming > VB.NET' 카테고리의 다른 글

VB.NET_LogFile  (0) 2015.08.04