C#
[C#] 파일 내용 읽고 한 줄씩 출력하기
J-sean
2025. 12. 29. 16:34
반응형
현재 디렉토리에서 모든 텍스트 파일을 불러와 읽고 한 줄씩 읽고 출력해 보자.
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
try
{
string[] files = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.txt");
if (files.Length == 0)
{
Console.WriteLine("No data.");
return;
}
foreach (string file in files)
Console.WriteLine(file);
List<string> strList = new List<string>();
// 2번 인덱스 파일 내용 읽기.
using (StreamReader sr = new StreamReader(files[2]))
{
while (!sr.EndOfStream)
strList.Add(sr.ReadLine()!); // !: null forgiving operator
}
for (int i = 0; i < strList.Count; i++)
Console.WriteLine($"{i}: {strList[i]}");
Random random = new Random();
int rand = random.Next(0, strList.Count);
Console.WriteLine($"Random: [{rand}] {strList[rand]}");
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
}
반응형