C# File I/O


파일 입출력 소개 (Introduction to File I/O)

파일 입출력(File I/O, Input/Output)은 컴퓨터 프로그램이 파일 시스템과 상호작용하는 방법을 의미합니다. C#에서는 System.IO 네임스페이스를 통해 파일 읽기, 쓰기, 삭제, 및 기타 파일 관련 작업을 수행할 수 있습니다. 파일 입출력 작업은 데이터 저장, 로깅, 구성 파일 처리 등 다양한 용도로 사용됩니다.

파일 읽기 (Reading Files)

파일에서 데이터를 읽는 작업은 여러 방법으로 수행할 수 있습니다. 기본적인 방법으로는 StreamReaderFile.ReadAllText 메서드를 사용할 수 있습니다.

예제: StreamReader를 사용한 파일 읽기 (Reading Files with StreamReader)

using System;
using System.IO;

namespace FileIOExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = "example.txt";

            try
            {
                using (StreamReader reader = new StreamReader(filePath))
                {
                    string content = reader.ReadToEnd();
                    Console.WriteLine("File content:");
                    Console.WriteLine(content);
                }
            }
            catch (IOException ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
}

이 예제는 StreamReader를 사용하여 파일의 전체 내용을 읽어옵니다. 파일이 존재하지 않거나 읽기 오류가 발생하면 예외를 처리합니다.

예제: File.ReadAllText를 사용한 파일 읽기 (Reading Files with File.ReadAllText)

using System;
using System.IO;

namespace FileIOExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = "example.txt";

            try
            {
                string content = File.ReadAllText(filePath);
                Console.WriteLine("File content:");
                Console.WriteLine(content);
            }
            catch (IOException ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
}

File.ReadAllText 메서드는 파일의 모든 텍스트를 한 번에 읽어 문자열로 반환합니다.

파일 쓰기 (Writing Files)

파일에 데이터를 쓰는 작업은 StreamWriter 또는 File.WriteAllText 메서드를 사용하여 수행할 수 있습니다.

예제: StreamWriter를 사용한 파일 쓰기 (Writing to Files with StreamWriter)

using System;
using System.IO;

namespace FileIOExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = "example.txt";
            string content = "This is a new file content.";

            try
            {
                using (StreamWriter writer = new StreamWriter(filePath))
                {
                    writer.Write(content);
                }
                Console.WriteLine("File written successfully.");
            }
            catch (IOException ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
}

StreamWriter를 사용하여 파일에 문자열을 씁니다. 파일이 존재하지 않으면 새로 생성됩니다.

예제: File.WriteAllText를 사용한 파일 쓰기 (Writing to Files with File.WriteAllText)

using System;
using System.IO;

namespace FileIOExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = "example.txt";
            string content = "This is a new file content.";

            try
            {
                File.WriteAllText(filePath, content);
                Console.WriteLine("File written successfully.");
            }
            catch (IOException ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
}

File.WriteAllText 메서드는 지정된 파일에 문자열을 쓰며, 파일이 이미 존재하는 경우 기존 내용을 덮어씁니다.

파일 추가 (Appending to Files)

파일에 내용을 추가할 때는 StreamWriter를 사용할 수 있으며, append 플래그를 설정하여 파일의 끝에 데이터를 추가할 수 있습니다.

예제: StreamWriter를 사용한 파일 추가 (Appending to Files with StreamWriter)

using System;
using System.IO;

namespace FileIOExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = "example.txt";
            string content = "This is additional content.";

            try
            {
                using (StreamWriter writer = new StreamWriter(filePath, append: true))
                {
                    writer.WriteLine(content);
                }
                Console.WriteLine("Content appended successfully.");
            }
            catch (IOException ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
}

이 예제에서는 StreamWriterappend 플래그를 true로 설정하여 기존 파일에 내용을 추가합니다.

파일 삭제 (Deleting Files)

파일을 삭제하려면 File.Delete 메서드를 사용할 수 있습니다.

예제: 파일 삭제 (Deleting Files)

using System;
using System.IO;

namespace FileIOExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = "example.txt";

            try
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                    Console.WriteLine("File deleted successfully.");
                }
                else
                {
                    Console.WriteLine("File does not exist.");
                }
            }
            catch (IOException ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
}

이 예제에서는 파일이 존재하는 경우에만 삭제 작업을 수행합니다.

파일 존재 여부 확인 (Checking If a File Exists)

파일의 존재 여부를 확인할 때는 File.Exists 메서드를 사용할 수 있습니다.

예제: 파일 존재 여부 확인 (Checking File Existence)

using System;
using System.IO;

namespace FileIOExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = "example.txt";

            if (File.Exists(filePath))
            {
                Console.WriteLine("File exists.");
            }
            else
            {
                Console.WriteLine("File does not exist.");
            }
        }
    }
}

이 예제에서는 파일의 존재 여부를 확인하고 결과를 출력합니다.

파일 정보 가져오기 (Getting File Information)

파일의 속성 및 정보를 가져오려면 FileInfo 클래스를 사용할 수 있습니다.

예제: 파일 정보 가져오기 (Getting File Information)

using System;
using System.IO;

namespace FileIOExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = "example.txt";
            FileInfo fileInfo = new FileInfo(filePath);

            if (fileInfo.Exists)
            {
                Console.WriteLine($"File Name: {fileInfo.Name}");
                Console.WriteLine($"File Size: {fileInfo.Length} bytes");
                Console.WriteLine($"Creation Time: {fileInfo.CreationTime}");
                Console.WriteLine($"Last Modified Time: {fileInfo.LastWriteTime}");
            }
            else
            {
                Console.WriteLine("File does not exist.");
            }
        }
    }
}

이 예제에서는 FileInfo 클래스를 사용하여 파일의 이름, 크기, 생성 시간 및 마지막 수정 시간을 출력합니다.

디렉터리 작업 (Directory Operations)

디렉터리를 생성, 삭제 및 목록을 가져오는 작업은 Directory 클래스를 통해 수행할 수 있습니다.

예제: 디렉터리 생성 (Creating a Directory)

using System;
using System.IO;

namespace FileIOExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string directoryPath = "example_directory";

            try
            {
                if (!Directory.Exists(directoryPath))
                {
                    Directory.CreateDirectory(directoryPath);
                    Console.WriteLine("Directory created successfully.");
                }
                else
                {
                    Console.WriteLine("Directory already exists.");
                }
            }
            catch (IOException ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
}

이 예제에서는 디렉터리가 존재하지 않으면 새로 생성합니다.

예제: 디렉터리 삭제 (Deleting a Directory)

using System;
using System.IO;

namespace FileIOExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string directoryPath = "example_directory";

            try
            {
                if (Directory.Exists(directoryPath))
                {
                    Directory.Delete(directoryPath, recursive: true);
                    Console.WriteLine("Directory deleted successfully.");
                }
                else
                {
                    Console.WriteLine("Directory does not exist.");
                }
            }
            catch (IOException ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
}

이 예제에서는 디렉터리를 삭제하며, recursive: true 플래그를 설정하여 디렉터리 내의 모든 파일과 서브디렉터리를 삭제합니다.

결론 (Conclusion)

C#에서 파일 입출력 작업은 System.IO 네임스페이스를 통해 수행됩니다. 파일 읽기, 쓰기, 삭제, 존재 여부 확인, 정보 가져오기 등의 작업을 통해 파일 시스템과 효율적으로 상호작용할 수 있습니다. `

StreamReader,StreamWriter,File,FileInfo,Directory` 클래스를 사용하여 다양한 파일 및 디렉터리 작업을 처리할 수 있으며, 예외 처리와 파일 존재 여부 확인을 통해 안정적인 파일 작업을 구현할 수 있습니다.


Posted in C#

Leave a Reply

Your email address will not be published. Required fields are marked *