C#
(C#) 텍스트 파일에 저장하기 생성하기
코딩ABC
2023. 6. 2. 21:50
반응형
다음 코드는 C#에서 텍스트 파일을 생성하고, 파일에 텍스트를 저장하는 코드입니다.
1. File 정적(static) 클래스 사용하기
using System;
using System.IO;
public class Program
{
public static void Main()
{
string textfile = @"c:\temp\MyTest.txt";
// 파일이 존재하지 않으면
if (!File.Exists(textfile))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(textfile))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
}
}
2. FileInfo 클래스를 이용해서 저장하기
using System;
using System.IO;
public class Program
{
public static void Main()
{
string textfile = @"c:\temp\MyTest.txt";
FileInfo fi = new FileInfo(textfile);
if (!fi.Exists) // 파일이 존재하지 않으면
{
//Create a file to write to.
using (StreamWriter sw = fi.CreateText())
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
}
}
반응형