[C#] 파일 내용 읽고 한 줄씩 출력하기
C# 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());
}
}
}
}
반응형
'C#' 카테고리의 다른 글
| [C#] 난수 생성, 배열 섞기, 리스트 컴프리헨션 (1) | 2025.12.30 |
|---|---|
| C# WinForm UI - MetroModernUI, MaterialSkin (0) | 2025.03.31 |
| C#에서 Python Script 실행하기 (0) | 2025.02.04 |
| C# Volume Auto Control Volume limit Program 자동 볼륨 조절 제한 프로그램 (0) | 2023.10.31 |
| C# Sound Meter 사운드 미터 (0) | 2023.10.28 |