티스토리 뷰

C#

파일 입출력

inasie 2009. 6. 26. 03:53

파일 입출력

파일은 FileStream이란 매개체 클래스를 통해 접근하여 읽고, 쓸 수 있다.

일반적으로 byte[]배열을 이용해 읽기/쓰기를 수행하며 사용법은 다음과 같다

 

FileStream fs = new FileStream("파일이름", FileMode.OpenOrCreate);

물론 생성자에 들어갈 수 있는 건 저것뿐만은 아니다. FileStream생성자는 15가지로 오버로딩 되어있다. 저렇게 사용할 경우 파일을 열되 없으면 생성하라라는 뜻이 되겠다.

 

오버로딩된 생성자는 다음과 같다. 위에서 사용한건 3번째거군

Name

Description

FileStream(IntPtr, FileAccess)

Obsolete. Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission.

FileStream(SafeFileHandle, FileAccess)

Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission.

FileStream(String, FileMode)

Initializes a new instance of the FileStream class with the specified path and creation mode.

FileStream(IntPtr, FileAccess, Boolean)

Obsolete. Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission and FileStream instance ownership.

FileStream(SafeFileHandle, FileAccess, Int32)

Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, and buffer size.

FileStream(String, FileMode, FileAccess)

Initializes a new instance of the FileStream class with the specified path, creation mode, and read/write permission.

FileStream(IntPtr, FileAccess, Boolean, Int32)

Obsolete. Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, FileStream instance ownership, and buffer size.

FileStream(SafeFileHandle, FileAccess, Int32, Boolean)

Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, buffer size, and synchronous or asynchronous state.

FileStream(String, FileMode, FileAccess, FileShare)

Initializes a new instance of the FileStream class with the specified path, creation mode, read/write permission, and sharing permission.

FileStream(IntPtr, FileAccess, Boolean, Int32, Boolean)

Obsolete. Initializes a new instance of the FileStream class for the specified file handle, with the specified read/write permission, FileStream instance ownership, buffer size, and synchronous or asynchronous state.

FileStream(String, FileMode, FileAccess, FileShare, Int32)

Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, and buffer size.

FileStream(String, FileMode, FileAccess, FileShare, Int32, Boolean)

Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, buffer size, and synchronous or asynchronous state.

FileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions)

Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and sharing permission, the access other FileStreams can have to the same file, the buffer size, and additional file options.

FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions)

Initializes a new instance of the FileStream class with the specified path, creation mode, access rights and sharing permission, the buffer size, and additional file options.

FileStream(String, FileMode, FileSystemRights, FileShare, Int32, FileOptions, FileSecurity)

Initializes a new instance of the FileStream class with the specified path, creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security.

 

어쨌든 파일을 열면 사용을 해야지!

 

1. 파일 읽기/쓰기 (byte[] 이용)

FileStream클래스에는 데이터를 byte로 읽고 쓸 수 있도록 메소드를 제공한다.

byte배열에 원하는 인덱스만큼 읽어오고 싶다면

Read()메소르를, 한바이트만 읽고 싶다면 ReadByte() 메소드를 사용하면된다.

Read

Reads a block of bytes from the stream and writes the data in a given buffer. (Overrides Stream..::.Read(array<Byte>[]()[], Int32, Int32).)

ReadByte

Reads a byte from the file and advances the read position one byte. (Overrides Stream..::.ReadByte()()().)

 

byte, byte[]로 쓰기 위한 함수 역시 Read와 마찬가지로 Write(), WirteByte()라는 함수가 존재한다.

Write

Writes a block of bytes to this stream using data from a buffer. (Overrides Stream..::.Write(array<Byte>[]()[], Int32, Int32).)

WriteByte

Writes a byte to the current position in the file stream. (Overrides Stream..::.WriteByte(Byte).)

이 밖에도 읽고 쓰기위한 여러가지 메소드들이 있으니 찾아보시길~!

 

2. 파일 읽기 쓰기 (string 이용)

우리가 많이 사용하는 건 byte가 아니라 string일 것이다. C#에서는 string이 쉽고 간편하기 때문에 많이들 사용한다. 때문에 string을 이용해 파일을 읽고 쓸 수 있도록 해주는 클래스가 존재한다.

StreamReaderStreamWriter라는 클래스이다.

(이건 파일을 읽고 쓸때만 쓰는 것은 아니다. Stream형태(MemoryStream, NetworkStream)의 바이너리 데이터를 마치 string처럼 사용할 수 있게 해주는 클래스라고 생각하면 된다.

 

생성자는 다음과 같다.

FileStream fs = new FileStream("파일이름", FileMode.OpenOrCreate);

StreamReader sr = new StreamReader(fs);

 

FileStream fs = new FileStream("파일이름", FileMode.OpenOrCreate);

StreamWriter sw = new StreamWriter(fs);

아 물론 생성자로 Stream객체 외에 여러가지가 들어갈 수 있다. StreamReader StreamWriter역시 여러가지로 오버로딩 되어있다.

 

StreamWrite의 생성자 오버로드 리스트

Name

Description

StreamWriter(Stream)

Initializes a new instance of the StreamWriter class for the specified stream, using UTF-8 encoding and the default buffer size.

StreamWriter(String)

Initializes a new instance of the StreamWriter class for the specified file on the specified path, using the default encoding and buffer size.

StreamWriter(Stream, Encoding)

Initializes a new instance of the StreamWriter class for the specified stream, using the specified encoding and the default buffer size.

StreamWriter(String, Boolean)

Initializes a new instance of the StreamWriter class for the specified file on the specified path, using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.

StreamWriter(Stream, Encoding, Int32)

Initializes a new instance of the StreamWriter class for the specified stream, using the specified encoding and buffer size.

StreamWriter(String, Boolean, Encoding)

Initializes a new instance of the StreamWriter class for the specified file on the specified path, using the specified encoding and default buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.

StreamWriter(String, Boolean, Encoding, Int32)

Initializes a new instance of the StreamWriter class for the specified file on the specified path, using the specified encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.

 

StreamReader의 생성자 오버로드 리스트

Name

Description

StreamReader(Stream)

Initializes a new instance of the StreamReader class for the specified stream.

StreamReader(String)

Initializes a new instance of the StreamReader class for the specified file name.

StreamReader(Stream, Boolean)

Initializes a new instance of the StreamReader class for the specified stream, with the specified byte order mark detection option.

StreamReader(Stream, Encoding)

Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding.

StreamReader(String, Boolean)

Initializes a new instance of the StreamReader class for the specified file name, with the specified byte order mark detection option.

StreamReader(String, Encoding)

Initializes a new instance of the StreamReader class for the specified file name, with the specified character encoding.

StreamReader(Stream, Encoding, Boolean)

Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding and byte order mark detection option.

StreamReader(String, Encoding, Boolean)

Initializes a new instance of the StreamReader class for the specified file name, with the specified character encoding and byte order mark detection option.

StreamReader(Stream, Encoding, Boolean, Int32)

Initializes a new instance of the StreamReader class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.

StreamReader(String, Encoding, Boolean, Int32)

Initializes a new instance of the StreamReader class for the specified file name, with the specified character encoding, byte order mark detection option, and buffer size.

이 역시 필요로 할 때 알아서 보기 바라며

 

우선 StremReader를 사용하여 string형식으로 읽어올 때 사용하는 메소드들은 다음과 같다.

Read

Overloaded. Reads the next character or next set of characters from the input stream.

ReadBlock

Reads a maximum of count characters from the current stream, and writes the data to buffer, beginning at index. (Inherited from TextReader.)

ReadLine

Reads a line of characters from the current stream and returns the data as a string. (Overrides TextReader..::.ReadLine()()().)

ReadToEnd

Reads the stream from the current position to the end of the stream. (Overrides TextReader..::.ReadToEnd()()().)

각각 1바이트 읽기, 특정 인덱스부터 인덱스까지 읽기, 한줄읽기, 끝까지 읽기가 되겠다.

( : string str = sr.ReadLine(); )

 

StreamWriter를 사용하여 string형식으로 파일을 쓸 때 사용하는 메소드들은 다음과 같다.

Write

Overloaded. Writes the given data type to a text stream.

WriteLine

Overloaded. Writes some data as specified by the overloaded parameters, followed by a line terminator.

Write : 문자 쓰기

WriteLine : 문자 쓰고 개행

 

이 밖에도 여러가지 메소드들을 제공하니 알아서 보길 바란다.

 

 

 

반응형
댓글