VB.NET 2008/VB - 파일 액세스

파일 액세스 - 파일 쓰기

본클라쓰 2011. 12. 23. 15:51

텍스트 쓰기

 

My.Computer.FileSystem.WriteAllText 메서드를 사용하여 파일에 텍스트를 쓸 수 있다. 지정된 파일이 없으면 새로 만들어진다.

 

My.Computer.FileSystem.WriteAllText("C:\TestFolder1\test.txt", "This is new text to be added.",True)

 

파일에 일련의 문자열을 쓰려면, 문자열 컬렉션을 순환하며 검색한다. WriteAllText 메서드를 사용하여 추가할 대상 파일과 문자열을 지정하고 Append를 true로 설정하여 파일에 텍스트를 쓴다.

 

For Each foundFile As String In My.Computer.FileSystem.GetFiles("C:\Documents and Settings")
    foundFile = foundFile & vbCrLf
    My.Computer.FileSystem.WriteAllText("C:\Documents and Settings\FileList.txt", foundFile, True)
Next

 

 

이진 파일 쓰기

 

My.Computer.FileSystem.WriteAllBytes 메서드는 데이터를 이진 파일에 쓴다. append 매개 변수가 true이면 데이터가 파일에 추가되고 그렇지 않으면 파일의 데이터가 덮어쓰여진다.

 

파일 이름을 제외한 지정된 경로가 올바르지 않으면 DirectoryNotFoundException 예외가 throw 된다. 경로는 올바르지만 파일이 없으면 파일이 만들어진다.

 

My.Computer.FileSystem.WriteAllBytes("C:\MyDocuments\CustomerData", CustomerData, True)

 

 

 

StreamWriter를 사용하여 파일에 텍스트 쓰기

 

My.Computer.FileSystem.OpenTextFileWriter 메서드를 사용하여 StreamWriter 개체를 열고 StreamWriter 클래스의 WriteLine 메서드를 사용하여 텍스트 파일에 문자열을 쓴다.

 

Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("c:\test.txt", True)
file.WriteLine("Here is the first string.")
file.Close()