vb :: 드라이브, 폴더, 파일처리 _파일에 데이터추가
텍스트 파일이 작성된 뒤 파일에 데이터를 추가하려면 다음 단계를 밟으면 된다.
- 파일열기 :: file.openAsTextStream 또는 fileSystemObject.openTextFile
- 데이터추가 :: write 또는 writeLine과 writeBlankLines 모두 textStream개체로 writeLine메서드는 지정된 문자열 끝에 줄바꿈 문자를 추가하고 커서를 다음라인 첫칸으로 이동한다.  writeBlankLines메서드는 새 줄을 텍스트파일에 추가하는 것이다.
- 파일닫기 :: textStream.close
 

#아래 예제는 3개의 쓰기 메서드 모두를 사용하여 파일을 열고 데이터를 추가하고 파일을 닫도록 한다.
사용자 삽입 이미지
소스코드Private Sub Command1_Click()
    Dim fso, txtfile
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set txtfile = fso.CreateTextFile("c:\my documents\test.txt", True)
   
    txtfile.Write ("테스트용입니다. ")
    txtfile.WriteLine ("테스트 1, 2, 3")
    txtfile.WriteBlankLines (3)
    txtfile.Write ("3줄 다음입니다.")
    txtfile.Close
End Sub


#파일읽기
텍스트파일에서 데이터를 읽으려면 다음 메서드들이 사용된다. 이들은 모두 textStream개체들이다.
메서드
설 명
read 파일에서 지정된 개수의 문자를 읽는다.
readLine 줄바꿈 문자(줄바꿈 문자제외)까지 한 줄 전체를 읽는다.
readAll 텍스트파일의 전체내용을 읽는다.
skip 지정한 문자를 뛰어 넘어 읽는다.
skipLine 지정한 줄을 뛰어 넘어 읽는다.

다음은 파일을 작성하여 쓰고, 다시 읽는 예제코드이다.
소스코드Private Sub Command1_Click()
    Dim fso As New FileSystemObject, txtfile, fil1 As File, ts As TextStream
    fso.CreateTextFile ("c:\my documents\read.txt")
   
    Set fil1 = fso.GetFile("c:\my documents\read.txt")
    Set ts = fil1.OpenAsTextStream(ForWriting)
   
    ts.WriteLine "안녕하십니까?"
    ts.WriteLine "반갑습니다."
    ts.Close
   
    Set ts = fil1.OpenAsTextStream(ForReading)
   
    Print ts.ReadLine
    Print ts.Read(3)
    ts.Close
End Sub


#파일 이동, 복사, 삭제
FSO모델에는 파일을 이동하고 복사하고 삭제하기 위한 메서드가 다음표처럼 각각 두개씩 있다.
메서드
설 명
file.move 또는 fileSystemObject.moveFile 파일 이동
file.copy 또는 fileSystemObject.copyFile 파일 복사
file.delete 또는 fileSystemObject.DeleteFile 파일 삭제
아래 예제는 c드라이브의 내문서폴더에 텍스트파일을 만들고 그 파일에 대한 정보를 작성하여 \tmp라는 폴더로 이동하고 \temp라는 폴더에 사본을 만들고 두 폴더 모두에서 사본들을 삭제한다.

이 예제를 실행하려면 내 문서폴더에 temp폴더와 tmp폴더가 있어야 한다.
소스코드Private Sub Command1_Click()
    Dim fso As New FileSystemObject, txtfile As TextStream, fil1, fil2 As File
   
    Set txtfile = fso.CreateTextFile("c:\my documents\test.txt", True)
    txtfile.Write ("테스트용입니다.")
    txtfile.Close
   
    Set fil1 = fso.GetFile("c:\my documents\test.txt")  '지정파일에 대한 핸들을 가져온다.
    fil1.Move ("c:\my documents\tmp\test.txt")
    fil1.Copy ("c:\my documents\temp\test.txt")
   
    Set fil1 = fso.GetFile("c:\my documents\tmp\test.txt")
    Set fil2 = fso.GetFile("c:\my documents\temp\test.txt")
    fil1.Delete
    fil2.Delete
End Sub
Posted by 나비:D
:
BLOG main image
by 나비:D

공지사항

카테고리

분류 전체보기 (278)
Programming? (0)
---------------------------.. (0)
나비의삽질 (5)
Application (177)
SQL (51)
Web (27)
etc. (14)
Omnia (0)
---------------------------.. (0)

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

달력

«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Total :
Today : Yesterday :