C#에서 파일 입출력을 처리하는 방법은?
_____A1: C 에서는 `System.IO` 네임스페이스의 `File.ReadAllText()`, `File.ReadAllLines()` 메서드를 사용하여 파일을 쉽게 읽을 수 있습니다. 예를 들어, `string content = File.ReadAllText("경로");`는 파일 전체 내용을 하나의 문자열로 읽어옵니다.
Q2: 파일에 데이터를 쓰려면 어떻게 해야 하나요?
A2: `File.WriteAllText()` 또는 `File.WriteAllLines()` 메서드를 사용해서 텍스트를 파일에 쓸 수 있습니다. 예시: `File.WriteAllText("경로", "내용");`는 지정한 파일에 문자열 내용을 덮어씁니다.
Q3: 파일을 한 줄씩 읽으면서 처리하려면?
A3: `StreamReader` 클래스를 사용하면 됩니다.
```csharp
using (StreamReader reader = new StreamReader("파일경로"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// 각 줄을 처리
}
}
```
`using` 문으로 자동 자원 해제를 권장합니다.
Q4: 파일에 내용을 추가(append)하려면 어떻게 하나요?
A4: `File.AppendAllText("경로", "추가할 내용");` 또는 `StreamWriter` 생성자에 `append:true` 옵션을 넣어 사용합니다.
```csharp
using (StreamWriter writer = new StreamWriter("파일경로", true))
{
writer.WriteLine("추가할 내용");
}
```
Q5: 바이너리 파일은 어떻게 읽고 쓰나요?
A5: `FileStream`과 `BinaryReader`, `BinaryWriter` 클래스를 사용합니다.
```csharp
using (FileStream fs = new FileStream("파일경로", FileMode.Open))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
// buffer에 데이터가 들어있음
}
```
쓰기 역시 `FileStream`과 `BinaryWriter`로 가능합니다.
A6: `File.Exists("파일경로")` 메서드를 사용합니다. 존재하면 `true`, 없으면 `false` 반환합니다.
Q7: 예외 처리는 어떻게 해야 하나요?
A7: 파일 입출력 시 예외가 자주 발생할 수 있으므로 `try-catch` 블록을 사용하여 `IOException`, `UnauthorizedAccessException` 등을 처리해야 합니다.
```csharp
try
{
string content = File.ReadAllText("파일경로");
}
catch (IOException ex)
{
// 입출력 오류 처리
}
catch (UnauthorizedAccessException ex)
{
// 권한 오류 처리
}
```
Q8: 비동기 방식으로 파일을 읽고 쓰려면?
A8: `File.ReadAllTextAsync()`, `File.WriteAllTextAsync()` 메서드를 사용하거나 `StreamReader`, `StreamWriter`의 비동기 메서드(`ReadLineAsync`, `WriteLineAsync`)를 사용합니다.
```csharp
string content = await File.ReadAllTextAsync("파일경로");
await File.WriteAllTextAsync("파일경로", "내용");
```
Q9: 텍스트 인코딩을 지정하려면?
A9: `StreamReader`나 `StreamWriter` 생성자에 `Encoding` 객체를 전달합니다.
```csharp
using (var reader = new StreamReader("파일경로", Encoding.UTF8)) { ... }
using (var writer = new StreamWriter("파일경로", false, Encoding.UTF8)) { ... }
```
Q10: 디렉터리 내 모든 파일 리스트를 얻으려면?
A10: `Directory.GetFiles("경로")` 또는 `Directory.EnumerateFiles("경로")`를 사용합니다.
```csharp
string[] files = Directory.GetFiles("폴더경로", "*.txt"); // 특정 확장자 필터링 가능
```
---
이 외에 `FileInfo`, `DirectoryInfo` 클래스를 이용한 객체 지향적 파일/폴더 처리 방법도 있습니다. 기본적으로 `System.IO` 네임스페이스에 다양한 클래스를 포함하고 있으며, 적절한 예외 처리와 자원 해제가 중요합니다.
이 네임스페이스는 파일 및 데이터 스트림을 읽고 쓰기 위한 다양한 클래스를 제공합니다.
아래에서는 파일 입출력의 기본적인 방법과 함께 몇 가지 주요 클래스를 소개하겠습니다.
1. 파일 읽기 및 쓰기 C 에서 파일을 읽고 쓰는 가장 기본적인 방법은 `File` 클래스와 `StreamReader`, `StreamWriter` 클래스를 사용하는 것입니다.
1.1. File 클래스 `File` 클래스는 파일을 생성, 삭제, 복사, 이동 및 열기와 같은 다양한 메서드를 제공합니다.
- 파일 쓰기 : ```csharp using System.IO; string filePath = "example.txt"; string content = "Hello, World!"; // 파일에 문자열을 쓰기 File.WriteAllText(filePath, content); ``` - 파일 읽기 : ```csharp // 파일에서 문자열을 읽기 string readContent = File.ReadAllText(filePath); Console.WriteLine(readContent); ``` 1.2. StreamReader 및 StreamWriter `StreamReader`와 `StreamWriter`는 파일을 스트림 방식으로 읽고 쓸 수 있게 해줍니다.
이 방법은 대용량 파일을 처리할 때 유용합니다.
- 파일 쓰기 : ```csharp using (StreamWriter writer = new StreamWriter(filePath)) { writer.WriteLine("Hello, World!"); writer.WriteLine("Welcome to C file I/O."); } ``` - 파일 읽기 : ```csharp using (StreamReader reader = new StreamReader(filePath)) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } } ```
2. 파일 및 디렉토리 관리 C 에서는 파일과 디렉토리를 관리하기 위한 다양한 메서드를 제공하는 `Directory` 클래스와 `FileInfo`, `DirectoryInfo` 클래스를 사용할 수 있습니다.
- 디렉토리 생성 : ```csharp string directoryPath = "exampleDir"; if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } ``` - 디렉토리 내 파일 목록 가져오기 : ```csharp string[] files = Directory.GetFiles(directoryPath); foreach (string file in files) { Console.WriteLine(file); } ``` - 파일 정보 가져오기 : ```csharp FileInfo fileInfo = new FileInfo(filePath); Console.WriteLine($"File Name: {fileInfo.Name}"); Console.WriteLine($"File Size: {fileInfo.Length} bytes"); ```
3. 비동기 파일 I/O C 에서는 비동기 방식으로 파일을 읽고 쓸 수 있는 메서드도 제공합니다.
이는 UI 응답성을 높이거나 대규모 데이터 처리를 할 때 유용합니다.
- 비동기 파일 쓰기 : ```csharp using (StreamWriter writer = new StreamWriter(filePath)) { await writer.WriteLineAsync("Hello, Async World!"); } ``` - 비동기 파일 읽기 : ```csharp using (StreamReader reader = new StreamReader(filePath)) { string content = await reader.ReadToEndAsync(); Console.WriteLine(content); } ```
4. 예외 처리 파일 입출력 작업은 다양한 예외가 발생할 수 있으므로, 항상 예외 처리를 고려해야 합니다.
예를 들어, 파일이 존재하지 않거나 읽기/쓰기 권한이 없을 경우 예외가 발생할 수 있습니다.
```csharp try { string content = File.ReadAllText(filePath); } catch (FileNotFoundException ex) { Console.WriteLine($"File not found: {ex.Message}"); } catch (UnauthorizedAccessException ex) { Console.WriteLine($"Access denied: {ex.Message}"); } catch (Exception ex) { Console.WriteLine($"An error occurred: {ex.Message}"); } ```
5. 파일 스트림 파일을 보다 세밀하게 제어하고 싶다면 `FileStream` 클래스를 사용할 수 있습니다.
이 클래스는 파일에 대한 바이트 스트림을 제공하며, 파일의 특정 위치에서 읽고 쓸 수 있는 기능을 제공합니다.
```csharp using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate)) { byte[] data = new UTF8Encoding(true).GetBytes("Hello, FileStream!"); fs.Write(data, 0, data.Length); } ``` 결론 C 에서 파일 입출력은 매우 유연하고 강력한 기능을 제공합니다.
`System.IO` 네임스페이스의 다양한 클래스를 활용하여 파일을 읽고 쓰는 기본적인 작업부터, 비동기 처리 및 파일 관리까지 다양한 작업을 수행할 수 있습니다.
이러한 기능들을 적절히 활용하여 효율적인 파일 입출력 처리를 구현할 수 있습니다.
작성자:
박서율 [비회원]
| 작성일자: 1년 전
2024-09-09 08:38:53
조회수: 231 | 댓글: 0 | 좋아요: 0 | 싫어요: 0
조회수: 231 | 댓글: 0 | 좋아요: 0 | 싫어요: 0
내용이 부정확하다면 싫어요를 클릭해주세요.