๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
C#/C# TIP

C#์˜ ์ž…์ถœ๋ ฅ(IO) - ํŒŒ์ผ ์ž…์ถœ๋ ฅ(File IO) ์ค‘์‹ฌ

by GREEN๋‚˜๋ฌด 2025. 6. 23.
728x90

 

๐Ÿ“ 6. ํŒŒ์ผ ์“ฐ๊ธฐ (File.WriteAllText, StreamWriter)

โœจ ๊ฐ„๋‹จํ•œ ํŒŒ์ผ ์ €์žฅ

using System.IO;

string path = "output.txt";
string content = "ํŒŒ์ผ์— ์ €์žฅํ•  ๋‚ด์šฉ์ž…๋‹ˆ๋‹ค.";

File.WriteAllText(path, content); // ๊ธฐ์กด ํŒŒ์ผ ๋ฎ์–ด์“ฐ๊ธฐ
Console.WriteLine("ํŒŒ์ผ ์ €์žฅ ์™„๋ฃŒ!");

โœจ ์—ฌ๋Ÿฌ ์ค„ ์“ฐ๊ธฐ

string[] lines = { "์ฒซ ์ค„", "๋‘˜์งธ ์ค„", "์…‹์งธ ์ค„" };
File.WriteAllLines("multi_line.txt", lines);

โœจ StreamWriter๋กœ ํ•œ ์ค„์”ฉ ์“ฐ๊ธฐ (append: ์ด์–ด์“ฐ๊ธฐ ๊ฐ€๋Šฅ)

using (StreamWriter writer = new StreamWriter("log.txt", append: true))
{
    writer.WriteLine("๋กœ๊ทธ ๊ธฐ๋ก ์‹œ์ž‘: " + DateTime.Now);
}

๐Ÿ“– 7. ํŒŒ์ผ ์ฝ๊ธฐ (File.ReadAllText, StreamReader)

โœจ ์ „์ฒด ํ…์ŠคํŠธ ์ฝ๊ธฐ

string content = File.ReadAllText("output.txt");
Console.WriteLine("์ฝ์€ ๋‚ด์šฉ:\n" + content);

โœจ ์ค„ ๋‹จ์œ„๋กœ ์ฝ๊ธฐ

string[] lines = File.ReadAllLines("multi_line.txt");

foreach (var line in lines)
{
    Console.WriteLine("์ฝ์€ ์ค„: " + line);
}

โœจ StreamReader๋กœ ํ•œ ์ค„์”ฉ ์ฝ๊ธฐ

using (StreamReader reader = new StreamReader("log.txt"))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(">> " + line);
    }
}

๐Ÿ” 8. ์‚ฌ์šฉ์ž ์ž…๋ ฅ ๋ฐ›์•„ ํŒŒ์ผ์— ์ €์žฅํ•˜๊ธฐ

Console.Write("์ €์žฅํ•  ๋‚ด์šฉ์„ ์ž…๋ ฅํ•˜์„ธ์š”: ");
string input = Console.ReadLine();
File.WriteAllText("user_input.txt", input);
Console.WriteLine("์ž…๋ ฅํ•œ ๋‚ด์šฉ์„ ์ €์žฅํ–ˆ์Šต๋‹ˆ๋‹ค.");

๐Ÿงฐ 9. ๊ธฐํƒ€ ํŒŒ์ผ ์ฒ˜๋ฆฌ ๊ธฐ๋Šฅ

string path = "sample.txt";

if (File.Exists(path))
{
    Console.WriteLine("ํŒŒ์ผ์ด ์กด์žฌํ•ฉ๋‹ˆ๋‹ค. ์‚ญ์ œํ•ฉ๋‹ˆ๋‹ค.");
    File.Delete(path);
}
else
{
    Console.WriteLine("ํŒŒ์ผ์ด ์—†์Šต๋‹ˆ๋‹ค. ์ƒˆ๋กœ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.");
    File.WriteAllText(path, "์ƒˆ ํŒŒ์ผ ์ƒ์„ฑ๋จ");
}

โœ… +

1. ํŒŒ์ผ ์“ฐ๊ธฐ ์‹œ ๊ธฐ์กด ๋‚ด์šฉ์„ ๋ฎ์–ด์“ฐ์ง€ ์•Š๊ณ  ์ด์–ด์“ฐ๋ ค๋ฉด?
→ StreamWriter์— append: true ์˜ต์…˜์„ ์ง€์ •ํ•ด์•ผ ํ•จ.

new StreamWriter("file.txt", append: true)

 

2. ํŒŒ์ผ์„ ํ•œ ์ค„์”ฉ ์ฒ˜๋ฆฌํ•ด์•ผ ํ•˜๋Š” ์ด์œ ๋Š”?
→ ๋Œ€์šฉ๋Ÿ‰ ํŒŒ์ผ์˜ ๊ฒฝ์šฐ ์ „์ฒด๋ฅผ ํ•œ ๋ฒˆ์— ์ฝ์œผ๋ฉด ๋ฉ”๋ชจ๋ฆฌ ๋ถ€์กฑ ๋ฌธ์ œ ๋ฐœ์ƒ ๊ฐ€๋Šฅ.
→ StreamReader์™€ while ๋ฌธ์œผ๋กœ ํ•œ ์ค„์”ฉ ์ฝ๋Š” ๋ฐฉ์‹์ด ์•ˆ์ „ํ•˜๊ณ  ํšจ์œจ์ ์ž„.

 

3. ์ฝ˜์†”๊ณผ ํŒŒ์ผ ์ž…์ถœ๋ ฅ์„ ๋ณ‘ํ–‰ํ•˜๋ ค๋ฉด ์–ด๋–ป๊ฒŒ ํ•ด์•ผ ํ• ๊นŒ?
→ ์ž…๋ ฅ์€ Console.ReadLine()์œผ๋กœ ๋ฐ›๊ณ , ์ถœ๋ ฅ์€ File.WriteAllText()๋กœ ํ•˜๋ฉด ๋จ.
→ ์˜ˆ์ œ:

Console.Write("์ €์žฅํ•  ์ด๋ฆ„ ์ž…๋ ฅ: ");
string name = Console.ReadLine();
File.WriteAllText("name.txt", $"์ด๋ฆ„: {name}");