본문 바로가기
Microsoft Scripting Runtime

File 개체

2023. 8. 13.

이 글은 도움말을 번역한 글입니다.

File 개체

파일의 모든 속성에 대한 액세스를 제공합니다.

 

비고

아래 코드에서는 File 개체를 가져오는 방법과 그 속성 중 하나를 보는 방법을 보여줍니다.

Sub CallShowFileInfo()

    Dim filePath As String
    
    filePath = "D:\download\Northwind.mdb"
    
    Call ShowFileInfo(filePath)
    
End Sub

Sub ShowFileInfo(filespec)

    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    
    s = f.DateCreated
    
    MsgBox "파일의 생성 날짜: " & s
    
End Sub

 

속성

Attributes Property

파일이나 폴더의 속성을 설정하거나 반환합니다. 속성에 따라 읽기/쓰기 또는 읽기 전용이 됩니다.

 

Syntax
object.Attributes [= newattributes ]

object : 필수적인 요소. 항상 File이나 Folder 개체의 이름입니다.

newattributes : 선택적인 요소. newattributes이 제공되는 경우 지정한 개체의 새로운 속성 값이 됩니다.

 

newattributes 요소의 값은 아래 값이나 그 값의 논리적 조합들 중 하나입니다.

 

아래 표는 FileAttribute 열거형 값입니다.

아래 코드는 파일에서 Attributes 속성의 사용법을 보여줍니다.

Sub CallSetClearArchiveBit()
    Dim filePath As String
    filePath = "D:\download\Northwind.mdb"
    Call SetClearArchiveBit(filePath)
End Sub

Sub SetClearArchiveBit(filespec)
    Dim fs, f, r
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    
    If f.Attributes And 32 Then
        r = MsgBox("아카이브 비트가 설정되어 있습니다. 해제하시겠습니까?", vbYesNo, "아카이브 비트 설정/해제")
        If r = vbYes Then
            f.Attributes = f.Attributes - 32
            MsgBox "아카이브 비트가 해제되었습니다."
        Else
            MsgBox "아카이브 비트는 설정된 상태입니다."
        End If
    Else
        r = MsgBox("아카이브 비트가 설정되어 있지 않습니다. 설정하시겠습니까?", vbYesNo, "아카이브 비트 설정/해제")
        If r = vbYes Then
            f.Attributes = f.Attributes + 32
            MsgBox "아카이브 비트가 설정되었습니다."
        Else
            MsgBox "아카이브 비트는 해제된 상태입니다."
        End If
    End If
End Sub

DateCreated Property

지정한 파일이나 폴더를 만든 날짜와 시간을 반환합니다. 읽기 전용 속성입니다.


Syntax
object.DateCreated

object는 항상 File이나 Folder 개체입니다.


비고
다음 코드는 파일에서 DateCreated 속성을 사용하는 방법을 보여줍니다.

Sub TestShowFileInfo()
    Dim filePath As String
    filePath = "D:\download\Northwind.mdb"
    
    ShowFileInfo filePath
End Sub

Sub ShowFileInfo(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = "Created: " & f.DateCreated
    MsgBox s
End Sub

DateLastAccessed Property

지정한 파일이나 폴더를 마지막으로 액세스한 날짜와 시간을 반환합니다. 읽기 전용 속성입니다.

 

Syntax
object.DateLastAccessed

 

object는 항상 File이나 Folder 개체입니다.

 

비고

아래 코드는 DateLastAccessed 속성을 파일에 사용하는 방법을 보여줍니다.

Sub ShowFileAccessInfo(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = UCase(filespec) & vbCrLf
    s = s & "Created: " & f.DateCreated & vbCrLf
    s = s & "Last Accessed: " & f.DateLastAccessed & vbCrLf
    s = s & "Last Modified: " & f.DateLastModified
    MsgBox s, 0, "File Access Info"
End Sub

Sub TestShowFileAccessInfo()
    Dim filePath As String
    filePath = "D:\download\Northwind.accdb"
    
    ShowFileAccessInfo filePath
End Sub

DateLastModified Property

지정한 파일이나 폴더를 마지막으로 수정한 날짜와 시간을 반환합니다. 읽기 전용 속성입니다.

 

Syntax
object.DateLastModified

 

object는 항상 File이나 Folder 개체입니다.

 

비고

아래 코드는 DateLastModified 속성을 파일에 사용하는 방법을 보여줍니다.

Sub ShowFileAccessInfo(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = UCase(filespec) & vbCrLf
    s = s & "Created: " & f.DateCreated & vbCrLf
    s = s & "Last Accessed: " & f.DateLastAccessed & vbCrLf
    s = s & "Last Modified: " & f.DateLastModified
    MsgBox s, 0, "File Access Info"
End Sub

Sub TestShowFileAccessInfo()
    Dim filePath As String
    filePath = "D:\download\Northwind.accdb"
    
    ShowFileAccessInfo filePath
End Sub

Drive Property

지정한 파일이나 폴더가 상주하는 드라이브의 드라이브 문자를 반환합니다. 읽기 전용 속성입니다.

 

Syntax
object.Drive

 

object는 항상 File이나 Folder 개체입니다.

 

비고

 

아래 코드는 Drive 속성의 사용법을 보여줍니다.

Sub ShowFileAccessInfo(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = f.name & " on Drive " & UCase(f.drive) & vbCrLf
    s = s & "Created: " & f.DateCreated & vbCrLf
    s = s & "Last Accessed: " & f.DateLastAccessed & vbCrLf
    s = s & "Last Modified: " & f.DateLastModified
    MsgBox s, 0, "File Access Info"
End Sub

Sub TestShowFileAccessInfo()
    Dim filePath As String
    filePath = "D:\download\Northwind.accdb"
    
    ShowFileAccessInfo filePath
End Sub

Name Property

지정한 파일이나 폴더의 이름을 지정하거나 반환합니다. 읽기/쓰기 속성입니다.

 

Syntax
object.Name [ = newname ]

 

object : 필수적인 요소. 항상 File이나 Folder 개체의 이름입니다.

newname : 선택적인 요소. newname이 제공되는 경우 이는 지정한 개체의 새 이름이 됩니다 .

 

비고

다음 코드는 파일과 함께 Name 속성을 사용하는 예시를 보여줍니다.

Sub ShowFileAccessInfo(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = f.name & " on Drive " & UCase(f.drive) & vbCrLf
    s = s & "Created: " & f.DateCreated & vbCrLf
    s = s & "Last Accessed: " & f.DateLastAccessed & vbCrLf
    s = s & "Last Modified: " & f.DateLastModified
    MsgBox s, 0, "File Access Info"
End Sub

Sub TestShowFileAccessInfo()
    Dim filePath As String
    filePath = "D:\download\Northwind.accdb"
    
    ShowFileAccessInfo filePath
End Sub

ParentFolder Property

지정한 파일이나 폴더의 부모 폴더 개체를 반환합니다. 읽기 전용 속성입니다.

 

Syntax
object.ParentFolder

 

object는 항상 File이나 Folder 개체입니다.

 

비고

다음 코드는 파일과 함께 ParentFolder 속성을 사용하는 예시를 보여줍니다.

Sub ShowFileAccessInfo(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = UCase(f.name) & " in " & UCase(f.parentFolder) & vbCrLf
    s = s & "Created: " & f.DateCreated & vbCrLf
    s = s & "Last Accessed: " & f.DateLastAccessed & vbCrLf
    s = s & "Last Modified: " & f.DateLastModified
    MsgBox s, 0, "File Access Info"
End Sub

Sub TestShowFileAccessInfo()
    Dim filePath As String
    filePath = "D:\download\Northwind.accdb"
    
    ShowFileAccessInfo filePath
End Sub

Path Property

지정한 파일, 폴더 또는 드라이브의 경로를 반환합니다.

 

Syntax
object.Path

 

object는 항상 File, Folder 또는 Drive 개체입니다.

 

비고

드라이브 문자의 경우 루트 드라이브는 포함되지 않습니다. 예를 들어 C 드라이브의 경로는 C:\가 아니라 C: 입니다.
파일의 경우 Path 속성에는 파일 이름과 확장명이 포함됩니다.

 

다음 코드는 파일 개체와 함께 Path 속성을 사용하는 방법을 보여줍니다.

Sub ShowFileAccessInfo(filespec)
    Dim fs, d, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = UCase(f.path) & vbCrLf
    s = s & "Created: " & f.DateCreated & vbCrLf
    s = s & "Last Accessed: " & f.DateLastAccessed & vbCrLf
    s = s & "Last Modified: " & f.DateLastModified
    MsgBox s, 0, "File Access Info"
End Sub

Sub TestShowFileAccessInfo()
    Dim filePath As String
    filePath = "D:\download\Northwind.accdb"
    
    ShowFileAccessInfo filePath
End Sub

ShortName Property

이전 8.3 명명 규칙을 요구하는 프로그램에서 사용하는 짧은 이름을 반환합니다.

 

Syntax
object.ShortName

 

object는 항상 File이나 Folder 개체입니다.

 

비고
아래 코드는 File 개체에 의한 ShortName 속성의 사용법을 보여줍니다.

Sub ShowShortName(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = "The short name for " & "" & UCase(f.name)
    s = s & "" & vbCrLf
    s = s & "is: " & "" & f.ShortName & ""
    MsgBox s, 0, "Short Name Info"
End Sub

Sub TestShowShortName()
    Dim filePath As String
    filePath = "D:\download\Excel 2013 Developer Documentation.chm"
    
    ShowShortName filePath
End Sub

* 8.3 파일 이름(ShortName)이 비활성화되어 있으면 작동하지 않습니다.


ShortPath Property

이전 8.3 파일 명명 규칙을 요구하는 프로그램에서 사용하는 짧은 경로를 반환합니다.

 

Syntax
object.ShortPath

 

object는 항상 File이나 Folder 개체입니다.

 

비고

아래 코드는 File 개체에 의한 ShortPath 속성의 사용법을 보여줍니다.

Function SelectFile() As String
    Dim selectedFilePath As String
    
    With Application.FileDialog(msoFileDialogFilePicker)
        .Title = "Select a file:"
        .AllowMultiSelect = False
        If .Show = -1 Then
            selectedFilePath = .SelectedItems(1)
        Else
        End If
    End With

    SelectFile = selectedFilePath
End Function

Sub ShowShortPathForFile(filePath As String)
    Dim fs As Object
    Set fs = CreateObject("Scripting.FileSystemObject")
    Dim file As Object
    Set file = fs.GetFile(filePath)
    
    Dim s As String
    s = "The short path for the selected file" & vbCrLf
    s = s & "is: " & file.ShortPath
    
    MsgBox s, vbInformation, "Short Path Info"
End Sub

Sub ShowShortPathForSelectedFile()
    Dim selectedFilePath As String
    selectedFilePath = SelectFile()
    
    If selectedFilePath <> "" Then
        ShowShortPathForFile selectedFilePath
    Else
        MsgBox "No file selected.", vbExclamation, "Error"
    End If
End Sub

* 8.3 파일 이름(ShortName)이 비활성화되어 있으면 작동하지 않습니다.

Size Property

파일인 경우 지정한 파일 크기를 바이트 단위로 반환하고, 폴더인 경우 해당 폴더의 모든 파일과 하위 폴더의 크기를 바이트 단위로 반환합니다.

 

Syntax
object.Size

object는 항상 File이나 Folder 개체입니다.

 

다음 코드는 File 개체와 함께 Size 속성을 사용하는 방법을 보여줍니다.

Sub ShowFileSize(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = UCase(f.Name) & " has a size of " & f.Size & " bytes."
    MsgBox s, 0, "File Size Info"
End Sub

Sub CallShowFileSize()
    Dim filePath As String
    ' 파일 경로를 설정합니다.
    filePath = "D:\download\Northwind.accdb"
    
    ' ShowFileSize 프로시저를 호출합니다.
    ShowFileSize filePath
End Sub

Type Property

파일이나 폴더의 형식에 관한 정보를 반환합니다. 예를 들어 .TXT로 끝나는 파일인 경우 "텍스트 문서"를 반환합니다.

 

Syntax
object.Type

object는 항상 File이나 Folder 개체입니다.

 

비고

다음 코드는 Type 속성을 사용하여 파일 유형을 반환하는 방법을 보여줍니다.

Sub ShowFileType(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = UCase(f.Name) & " is a " & f.Type
    MsgBox s, 0, "File Type Info"
End Sub

Sub CallShowFileType()
    Dim filePath As String
    ' 파일 경로를 설정합니다.
    filePath = "D:\download\anatomy.pdf"
    
    ' ShowFileType 프로시저를 호출합니다.
    ShowFileType filePath
End Sub

메서드

Copy Method

지정한 파일이나 폴더를 한 위치에서 다른 위치로 복사합니다.

 

Syntax
object.Copy destination, [ overwrite ]

 

object : 필수적인 요소. 항상 File이나 Folder 개체의 이름입니다.
destination : 필수적인 요소. 파일이나 폴더를 복사해 놓을 대상 위치를 나타내는 문자열입니다. 와일드카드 문자는 사용할 수 없습니다.
overwrite : 선택적인 요소. 기존 파일이나 폴더에 덮어 쓰면 True(기본값), 그렇지 않으면 False인 Boolean 값입니다.

 

비고

File이나 Folder 개체에 대한 Copy 메서드의 결과는 object에서 참조하는 파일이나 폴더를 인수로 전달하는 FileSystemObject.CopyFile이나 FileSystemObject.CopyFolder를 사용하여 수행되는 동작과 일치합니다. 그러나 다른 메서드로도 여러 파일이나 폴더를 복사할 수 있습니다.

 

다음 코드는 Copy 메서드 사용법을 보여줍니다.

Sub CopyFileUsingFileObject(sourcePath, destinationPath, Optional overwrite As Boolean = True)
    Dim fs As Object
    Dim sourceFile As Object
    Dim destinationFolder As Object

    On Error GoTo ErrorHandler ' 오류 발생 시 처리를 위한 레이블

    Set fs = CreateObject("Scripting.FileSystemObject")

    ' 원본 파일과 대상 폴더 개체를 가져옵니다.
    Set sourceFile = fs.GetFile(sourcePath)
    Set destinationFolder = fs.GetFolder(fs.GetParentFolderName(destinationPath))

    ' 원본 파일이 존재하는지 확인합니다.
    If fs.FileExists(sourcePath) Then
        ' 대상 파일이 이미 존재하면 덮어쓸지 여부를 결정합니다.
        If fs.FileExists(destinationPath) And Not overwrite Then
            MsgBox "대상 파일이 이미 존재합니다. 복사 작업이 취소되었습니다.", vbExclamation, "파일 복사"
        Else
            ' 파일을 복사합니다.
            sourceFile.Copy destinationPath, overwrite
            MsgBox "파일이 성공적으로 복사되었습니다.", vbInformation, "파일 복사"
        End If
    Else
        MsgBox "원본 파일이 존재하지 않습니다.", vbExclamation, "파일 복사"
    End If

    Exit Sub ' 정상적으로 종료될 경우 처리를 위한 레이블
ErrorHandler:
    MsgBox "파일 복사 작업 중 오류가 발생했습니다.", vbCritical, "파일 복사 오류"
End Sub

Sub CallCopyFileUsingFileObject()
    Dim sourceFilePath As String
    Dim destinationFilePath As String

    ' 복사할 파일의 경로를 설정합니다.
    sourceFilePath = "D:\SourceFolder\Northwind.accdb"

    ' 대상 폴더와 파일 이름을 설정합니다.
    destinationFilePath = "D:\DestinationFolder\Northwind.accdb"

    ' CopyFileUsingFileObject 프로시저를 호출하여 파일을 복사합니다.
    CopyFileUsingFileObject sourceFilePath, destinationFilePath
End Sub

Delete Method

지정한 파일이나 폴더를 삭제합니다.

 

object.Delete force

 

object : 필수적인 요소. 항상 File이나 Folder 개체의 이름입니다.

force : 선택적인 요소. 읽기 전용 속성의 파일이나 폴더를 삭제할 경우 True, 그렇지 않으면 False(기본값)인 Boolean 값입니다.

 

비고

지정한 파일이나 폴더가 존재하지 않으면 오류가 일어납니다. Delete 메서드에서는 폴더의 내용 유무를 구분하지 않습니다. 따라서 지정한 폴더는 그 내용의 유무에 상관없이 삭제됩니다.

 

File이나 Folder 개체에 대한 Delete 메서드의 결과는 FileSystemObject.DeleteFile이나FileSystemObject.DeleteFolder를 사용하여 수행되는 동작과 일치합니다.

 

아래 예제는 Delete 메서드 사용법을 보여줍니다.

Sub DeleteFile(filePath)
    Dim fs As Object
    Dim fileToDelete As Object
    
    On Error GoTo ErrorHandler ' 오류 발생 시 처리를 위한 레이블

    Set fs = CreateObject("Scripting.FileSystemObject")
    
    If fs.FileExists(filePath) Then
        ' 파일 개체를 가져옵니다.
        Set fileToDelete = fs.GetFile(filePath)
        
        ' 파일을 삭제합니다.
        fileToDelete.Delete
        
        If Not fs.FileExists(filePath) Then
            MsgBox "파일이 성공적으로 삭제되었습니다.", vbInformation, "파일 삭제"
        End If
    Else
        MsgBox "삭제할 파일이 존재하지 않습니다.", vbExclamation, "파일 삭제"
    End If
    
    Exit Sub ' 정상적으로 종료될 경우 처리를 위한 레이블
ErrorHandler:
    MsgBox "파일 삭제 중 오류가 발생했습니다.", vbCritical, "파일 삭제 오류"
End Sub

Sub CallDeleteFile()
    Dim filePath As String

    ' 삭제할 파일의 경로를 설정합니다.
    filePath = "D:\Example\sample.txt"
    
    ' DeleteFile 프로시저를 호출하여 파일을 삭제합니다.
    DeleteFile filePath
End Sub

Move Method

지정한 파일이나 폴더를 한 위치에서 다른 위치로 옮깁니다.

 

Syntax

object.Move destination

 

object : 필수적인 요소. 항상 File이나 Folder 개체의 이름입니다.

destination : 필수적인 요소. 파일이나 폴더를 옮겨 놓을 대상 위치를 나타내는 문자열입니다. 와일드카드 문자는 사용할 수 없습니다.

 

비고

File이나 Folder 개체에 대한 Move 메서드의 결과는 FileSystemObject.MoveFile이나 FileSystemObject.MoveFolder를 사용하여 수행되는 동작과 일치합니다. 그러나 다른 메서드로도 여러 파일이나 폴더를 옮길 수 있습니다.

아래 예제는 Move 메서드의 사용법을 보여줍니다.

Sub MoveFile(sourcePath, destinationPath)
    Dim fs As Object
    Dim fileToMove As Object

    On Error GoTo ErrorHandler    ' 오류 발생 시 처리를 위한 레이블

    Set fs = CreateObject("Scripting.FileSystemObject")

    If fs.FileExists(sourcePath) Then
        ' 파일 개체를 가져옵니다.
        Set fileToMove = fs.GetFile(sourcePath)

        ' 파일을 이동합니다.
        fileToMove.Move destinationPath

        If fs.FileExists(destinationPath) Then
            MsgBox "파일이 성공적으로 이동되었습니다.", vbInformation, "파일 이동"
        Else
        End If
    Else
        MsgBox "이동할 파일이 존재하지 않습니다.", vbExclamation, "파일 이동"
    End If

    Exit Sub    ' 이 부분이 없으면 ErrorHandler을 실행하므로 프로시저를 종료합니다.
ErrorHandler:
    MsgBox "파일 이동 중 오류가 발생했습니다.", vbCritical, "파일 이동 오류"
End Sub


Sub CallMoveFile()
    Dim sourceFilePath As String
    Dim destinationFilePath As String

    ' 이동할 파일의 경로를 설정합니다.
    sourceFilePath = "D:\SourceFolder\sample.txt"

    ' 대상 폴더와 파일 이름을 설정합니다.
    destinationFilePath = "D:\DestinationFolder\sample.txt"

    ' MoveFile 프로시저를 호출하여 파일을 이동합니다.
    MoveFile sourceFilePath, destinationFilePath
End Sub

OpenAsTextStream Method

지정한 파일을 열고, 그 파일을 읽거나 쓰거나 추가하는 데 사용될 수 있는 TextStream 개체를 반환합니다.

 

Syntax
object.OpenAsTextStream ([ iomode, [ format ]])

 

object : 필수적인 요소. 항상 File 개체의 이름입니다.

iomode : 선택적인 요소. 입/출력 모드를 나타냅니다. 세 상수, 즉 ForReading, ForWriting 또는 ForAppending 중 하나이면 됩니다.

format : 선택적인 요소. 세 개의 Tristate 값 중 하나를 사용하여 열릴 파일의 형식을 나타냅니다. 생략하면 파일은 ASCII 형식으로 열립니다.

 

설정

 

iomode 요소는 아래 설정 중 하나입니다.

format 요소는 아래 설정 중 하나입니다.

비고

OpenAsTextStream 메서드는 FileSystemObject 개체의 OpenTextFile 메서드와 동일한 기능을 제공합니다. 또한 OpenAsTextStream 메서드를 사용하여 파일에 쓸 수 있습니다.

 

아래 코드는 OpenAsTextStream 메서드의 사용법을 보여줍니다.

Sub TextStreamTest()
    Const ForReading = 1, ForWriting = 2, ForAppending = 8
    Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
    Dim fs, f, ts, s
    
    Set fs = CreateObject("Scripting.FileSystemObject")
    
    fs.CreateTextFile "test1.txt"
    
    Set f = fs.GetFile("test1.txt")
    Set ts = f.OpenAsTextStream(ForWriting, TristateUseDefault)
    
    ts.Write "Hello World"
    ts.Close
    
    Set ts = f.OpenAsTextStream(ForReading, TristateUseDefault)
    
    s = ts.ReadLine
    MsgBox s
    ts.Close
    
End Sub

Sub CallTextStreamTest()
    TextStreamTest
End Sub

'Microsoft Scripting Runtime' 카테고리의 다른 글

TextStream 개체  (0) 2023.08.14
Files 컬렉션  (0) 2023.08.13
Folder 개체  (0) 2023.08.10
Folders 컬렉션  (0) 2023.08.10
Drive 개체  (0) 2023.08.10