C#에서 파일 입출력(I/O)은 어떻게 하나요?
_____A1: 가장 간단한 방법은 `System.IO.File` 클래스의 정적 메서드를 사용하는 것입니다. 예를 들어, `File.ReadAllText(string path)` 메서드를 사용해 파일 전체 내용을 문자열로 읽을 수 있습니다.
```csharp
string content = File.ReadAllText("example.txt");
Console.WriteLine(content);
```
---
Q2: 파일에 텍스트를 쓰려면 어떻게 하나요?
A2: `File.WriteAllText(string path, string contents)` 메서드를 사용하면 지정한 경로에 문자열을 파일로 씁니다. 기존 파일이 있으면 덮어쓰고, 없으면 새로 만듭니다.
```csharp
File.WriteAllText("output.txt", "Hello, world!");
```
---
Q3: 한 줄씩 파일을 읽고 싶으면 어떻게 하나요?
A3: `File.ReadLines(string path)` 또는 `File.ReadAllLines(string path)` 메서드를 사용하면 됩니다. `ReadLines`는 열거자를 반환하여 메모리를 적게 사용하며, `ReadAllLines`는 전체를 배열로 읽습니다.
```csharp
foreach (string line in File.ReadLines("example.txt"))
{
Console.WriteLine(line);
}
```
---
Q4: 파일에 여러 줄을 쓰고 싶을 때는?
A4: 문자열 배열을 `File.WriteAllLines(string path, IEnumerable
```csharp
string[] lines = { "First line", "Second line", "Third line" };
File.WriteAllLines("output.txt", lines);
```
---
Q5: 파일을 열고 스트림을 사용해 읽거나 쓰려면?
A5: `FileStream`, `StreamReader`, `StreamWriter` 클래스를 사용합니다. 예를 들어, `StreamReader`로 텍스트를 순차적으로 읽거나 `StreamWriter`로 쓸 수 있습니다.
```csharp
using (StreamReader reader = new StreamReader("example.txt"))
{
string line;
while((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
using (StreamWriter writer = new StreamWriter("output.txt"))
{
writer.WriteLine("Hello from StreamWriter");
}
```
---
Q6: 파일 모드를 직접 지정할 수 있나요?
A6: 네, `FileStream` 생성자에서 `FileMode`(예: Open, Create, Append), `FileAccess`(읽기, 쓰기, 읽기/쓰기), `FileShare` 옵션을 지정할 수 있습니다.
```csharp
using (FileStream fs = new FileStream("example.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
// 파일 스트림 사용
}
```
---
Q7: 파일 존재 여부를 확인하려면?
A7: `File.Exists(string path)` 메서드를 사용해 해당 경로에 파일이 존재하는지 불리언 값으로 확인할 수 있습니다.
```csharp
if (File.Exists("example.txt"))
{
Console.WriteLine("파일이 있습니다.");
}
else
{
Console.WriteLine("파일이 없습니다.");
}
```
---
Q8: 바이너리 파일을 읽고 쓸 수 있나요?
A8: 네, `FileStream` 또는 `BinaryReader`/`BinaryWriter`를 사용해 바이너리 데이터를 처리할 수 있습니다.
```csharp
using (BinaryWriter bw = new BinaryWriter(File.Open("data.bin", FileMode.Create)))
{
bw.Write(123);
bw.Write("Hello");
}
using (BinaryReader br = new BinaryReader(File.Open("data.bin", FileMode.Open)))
{
int number = br.ReadInt32();
string text = br.ReadString();
Console.WriteLine($"{number}, {text}");
}
```
---
Q9: 비동기 방식으로 파일을 읽고 쓰는 방법은?
A9: `File.ReadAllTextAsync`, `File.WriteAllTextAsync`, `StreamReader.ReadLineAsync` 등 비동기 메서드를 사용해 비동기 처리할 수 있습니다.
```csharp
string content = await File.ReadAllTextAsync("example.txt");
await File.WriteAllTextAsync("output.txt", "Async hello!");
```
---
Q10: 예외 처리는 어떻게 해야 하나요?
A10: 파일 입출력 중에는 `IOException`, `UnauthorizedAccessException`, `FileNotFoundException` 등 다양한 예외가 발생할 수 있으므로 `try-catch` 구문으로 안전하게 처리하는 것이 좋습니다.
```csharp
try
{
string content = File.ReadAllText("example.txt");
}
catch (IOException ex)
{
Console.WriteLine($"I/O 오류: {ex.Message}");
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine($"권한 오류: {ex.Message}");
}
```
---
요약: C 에서 파일 입출력은 `System.IO` 네임스페이스 내의 `File`, `FileStream`, `StreamReader`, `StreamWriter` 클래스를 주로 사용하며, 동기/비동기 방식 모두 지원하고 예외 처리를 적절히 해주는 것이 중요합니다.
이 네임스페이스는 파일 및 디렉터리 작업을 위한 다양한 기능을 제공합니다.
다음은 C 에서 파일 입출력을 수행하는 방법에 대한 자세한 설명입니다.
1. 파일 읽기 및 쓰기 1.1. 파일 쓰기 파일에 데이터를 쓰기 위해서는 `StreamWriter` 클래스를 사용할 수 있습니다.
이 클래스는 텍스트 파일에 문자열을 작성하는 데 유용합니다.
```csharp using System; using System.IO; class Program { static void Main() { string filePath = "example.txt"; // StreamWriter를 사용하여 파일에 쓰기 using (StreamWriter writer = new StreamWriter(filePath)) { writer.WriteLine("Hello, World!"); writer.WriteLine("This is a test file."); } Console.WriteLine("파일에 데이터가 성공적으로 기록되었습니다.
"); } } ``` 위의 코드에서 `using` 블록을 사용하여 `StreamWriter` 객체를 생성했습니다.
`using` 블록을 사용하면 작업이 끝난 후 자동으로 리소스가 해제됩니다.
1.2. 파일 읽기 파일에서 데이터를 읽기 위해서는 `StreamReader` 클래스를 사용할 수 있습니다.
```csharp using System; using System.IO; class Program { static void Main() { string filePath = "example.txt"; // StreamReader를 사용하여 파일 읽기 using (StreamReader reader = new StreamReader(filePath)) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } } } } ``` 위의 코드에서는 `StreamReader`를 사용하여 파일의 각 줄을 읽고 콘솔에 출력합니다.
2. 파일 존재 여부 확인 파일이 존재하는지 확인하려면 `File.Exists` 메서드를 사용할 수 있습니다.
```csharp string filePath = "example.txt"; if (File.Exists(filePath)) { Console.WriteLine("파일이 존재합니다.
"); } else { Console.WriteLine("파일이 존재하지 않습니다.
"); } ```
3. 파일 복사, 이동 및 삭제 C 에서는 파일을 복사, 이동 및 삭제하는 데 사용할 수 있는 메서드가 제공됩니다.
3.1. 파일 복사 ```csharp string sourceFile = "example.txt"; string destinationFile = "example_copy.txt"; File.Copy(sourceFile, destinationFile, true); // true는 덮어쓰기를 의미 ```
3.2. 파일 이동 ```csharp string sourceFile = "example.txt"; string destinationFile = "example_moved.txt"; File.Move(sourceFile, destinationFile); ```
3.3. 파일 삭제 ```csharp string filePath = "example.txt"; if (File.Exists(filePath)) { File.Delete(filePath); Console.WriteLine("파일이 삭제되었습니다.
"); } ```
4. 비동기 파일 I/O C 에서는 비동기 파일 작업을 위한 메서드도 제공합니다.
`FileStream` 클래스와 `StreamReader`, `StreamWriter`의 비동기 메서드를 사용할 수 있습니다.
4.1. 비동기 파일 쓰기 ```csharp using System; using System.IO; using System.Threading.Tasks; class Program { static async Task Main() { string filePath = "example_async.txt"; using (StreamWriter writer = new StreamWriter(filePath)) { await writer.WriteLineAsync("Hello, Async World!"); } Console.WriteLine("비동기 파일 쓰기가 완료되었습니다.
"); } } ```
4.2. 비동기 파일 읽기 ```csharp using System; using System.IO; using System.Threading.Tasks; class Program { static async Task Main() { string filePath = "example_async.txt"; using (StreamReader reader = new StreamReader(filePath)) { string content = await reader.ReadToEndAsync(); Console.WriteLine(content); } } } ```
5. 파일 및 디렉터리 작업 C 에서는 파일뿐만 아니라 디렉터리 작업도 쉽게 수행할 수 있습니다.
`Directory` 클래스를 사용하여 디렉터리를 생성, 삭제, 이동 및 나열할 수 있습니다.
5.1. 디렉터리 생성 ```csharp string directoryPath = "example_directory"; if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); Console.WriteLine("디렉터리가 생성되었습니다.
"); } ```
5.2. 디렉터리 삭제 ```csharp if (Directory.Exists(directoryPath)) { Directory.Delete(directoryPath, true); // true는 하위 디렉터리 및 파일을 포함하여 삭제 Console.WriteLine("디렉터리가 삭제되었습니다.
"); } ```
5.3. 디렉터리 내용 나열 ```csharp string[] files = Directory.GetFiles(directoryPath); foreach (string file in files) { Console.WriteLine(file); } ``` 결론 C 에서 파일 입출력(I/O)은 `System.IO` 네임스페이스의 다양한 클래스를 통해 쉽게 수행할 수 있습니다.
파일을 읽고 쓰는 기본적인 방법부터 비동기 작업, 디렉터리 작업까지 다양한 기능을 제공하므로, 필요에 따라 적절한 방법을 선택하여 사용할 수 있습니다.
이러한 기능들을 활용하여 파일 기반의 애플리케이션을 개발하는 데 큰 도움이 될 것입니다.
작성자:
김민지 [비회원]
| 작성일자: 1년 전
2024-09-09 08:39:12
조회수: 179 | 댓글: 0 | 좋아요: 0 | 싫어요: 0
조회수: 179 | 댓글: 0 | 좋아요: 0 | 싫어요: 0
내용이 부정확하다면 싫어요를 클릭해주세요.