{ 스트림, 예외, 문자 읽기, 문자쓰기, 바이너리 읽고 쓰기, 키보드 입력 }
저장 개념 DB(데이터 베이스) 사용
스트림
파일의 종류
1. 텍스트 파일 -> C#프로그램 소스 / HTML
2. 바이너리 파일 -> 음성파일 / 그림파일
바이너리 파일은 텍스트 에디터에서는 문자로 읽을 수가 없다.
파일의 읽기 및 쓰기에 대한 데이터의 흐름을 스트림이라고 함.
C#읽기 쓰기 스트림을 위한 클래스 -> System.IO;
예외(Exception : 익셉션)
컴파일한 파일을 실행하면 오류가 일어나는 경우 이 오류를 예외라고 한다.
예외 처리를 해 두면 비정상 종료를 막을 수 있음
try ~ chatch ~ finally
try
{
예외가 발생할지도 모르는 처리
}
catch(Exception e 예외 클래스명 변수명)
{
예외 발생 시에 실행하는 처리
}
finally
{
뒷마무리 작업, 예외가 발생했는지 여부와 관계없이 실행
}
문자 읽기
file1.txt -> UTF - 8 형식으로 실행파일과 같은 위치에 만들어두기
//1. 파일 열기 : FileStream 클래스를 사용하여 스트림을 만들고
FileStream fs = new FileStream("file1.txt" //파일명 , FileMode.Open //열기 모드(파일의 여는 방법을 지정) );
StreamReader r = new StreamReader(fs);
//2. 데이터 읽기
string s = r.ReadLine();
r.Close();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO; //스트림을 위한 클래스 준비
namespace 파일스트림
{
internal class Program
{
static void Main(string[] args)
{
FileStream fs; //파일시스템 변수선언
try
{
fs = new FileStream("Alpha.txt", FileMode.Open);
}
catch(IOException) //IOException 파일쪽만 Exception 전체 (속도차이)
{
Console.WriteLine("파일을 열 수 없습니다.");
return;
}
StreamReader r = new StreamReader(fs);
string s;
int i = 1;
while((s = r.ReadLine()) != null) //파일의 문자열을 읽고 값이 있으면 계속읽기
{
Console.WriteLine(i + ":"+s); i++;
}
r.Close(); //파일은 잘 닫아줘야한다.
}
}
}
문자 쓰기
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 파일쓰기
{
internal class Program
{
static void Main(string[] args)
{
FileStream fs;
try
{
fs = new FileStream("file2.txt", FileMode.Create);
}
catch(IOException)
{
Console.WriteLine("파일을 열 수 없습니다.");
return;
}
StreamWriter w = new StreamWriter(fs);
w.WriteLine("열심히 합시다. 부자되세요");
w.Close();
}
}
}
참고
https://learn.microsoft.com/ko-kr/dotnet/api/system.io.filemode?view=net-7.0
FileMode 열거형 (System.IO)
운영 체제에서 파일을 여는 방법을 지정합니다.
learn.microsoft.com
바이너리 읽고 쓰기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace 바이너리읽고쓰기
{
internal class Program
{
static void Main(string[] args)
{
// 읽기
/* int a = 1;
string b = "1234";
byte[] arrData = { 0x01, 0x02, 0x03 };
Stream stream = new FileStream("test.bin", FileMode.OpenOrCreate);
BinaryWriter wr = new BinaryWriter(stream);
wr.Write(a);
wr.Write(b);
wr.Write(arrData);*/
// 쓰기
BinaryReader br = new BinaryReader(File.Open("test.bin", FileMode.Open));
int a;
string b;
byte[] arrData = new byte[3];
a = br.ReadInt32();
b = br.ReadString();
arrData = br.ReadBytes(3);
Console.WriteLine("a:{0}", a);
Console.WriteLine("b:{0}", b);
for(int i = 0; i < arrData.Length; i++)
{
Console.WriteLine("c:{0:x2}", arrData[i]);
}
}
}
}
키보드입력
namespace 키보드입력
{
internal class Program
{
static void Main(string[] args)
{
//1부터 30까지의 무작위 정수를 생성
Random rnd = new Random();
int a = rnd.Next(1, 31);
Console.WriteLine("1부터 30까지의 값을 입력하여 주십시오.");
while(true)
{
string s = Console.ReadLine();
//아무 것도 입력하지 않고 Enter를 누르면 종료
if(s == "")
{
Console.WriteLine("종료합니다.");
break;
}
int n = 0;
try
{
//입력 문자열을 숫자로 변환
n = int.Parse(s);
}
catch(FormatException e)
{
Console.WriteLine(e.Message);
Console.WriteLine("1부터 30까지의 값을 입력해주세요");
continue;
}
if(n == a)
{
Console.WriteLine("맞습니다.");
break;
}
else if(n > a)
{
Console.WriteLine("너무 큽니다.");
}
else if(n < a)
{
Console.WriteLine("너무 작습니다.");
}
}
}
}
}
예제 프로그램
근무 시간 기록표
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace timecard
{
internal class Program
{
const string fn = "times.txt"; // const 변수의 값이 계속 변하지 않음을 나타냄
static bool appendTime(bool goWork)
{
DateTime dt = DateTime.Now; //현재 시각을 가져옴
string mode = goWork ? "출근" : "퇴근"; //조건 연산자 조건식 ? true : false;
string s = mode + " " + dt.Year + "/" + dt.Month + "/" + dt.Day + " " + dt.Hour + ":" + dt.Minute;
//파일쓰기
try
{
//파일열기
FileStream fs = new FileStream(fn, FileMode.Append); //FileMode.Append 추가기록모드로 열기. 파일이 없으면 만들기
StreamWriter w = new StreamWriter(fs);
//데이터쓰기
w.WriteLine(s); //시각 데이터를 파일에 씀
//파일닫기
w.Close();
}
catch (IOException)
{
Console.WriteLine("쓰기에 실패했습니다.");
return false;
}
Console.WriteLine(s);
return true;
}
static void listTime() //알람을 작성하여 표시하기 위한 메소드
{
string s;
//파일 읽기
try
{
FileStream fs = new FileStream(fn, FileMode.Open);
StreamReader r = new StreamReader(fs);
s = r.ReadLine(); //시각 데이터를 기록한 파일을 읽음
while (s != null)
{
Console.WriteLine(s);
s = r.ReadLine(); //다음 회 분의 읽기
}
r.Close();
}
catch (IOException)
{
Console.WriteLine("알지 못했습니다.");
return;
}
}
static void usage()
{
Console.WriteLine("명령을 입력해 주세요");
Console.WriteLine("i:출력 o :퇴근 l:알람 q:종료");
}
static void Main()
{
usage();
while(true)
{
Console.Write(">"); //프롬프트의 '>'를 표시
string cmd = Console.ReadLine();
if (cmd == "i")
appendTime(true);
else if (cmd == "o")
appendTime(false);
else if (cmd == "l")
listTime();
else if (cmd == "q")
break;
else
usage();
}
}
}
}
'프로그래밍 > C#' 카테고리의 다른 글
[유니티] Rigidbody 중력 제어 (0) | 2023.07.27 |
---|---|
[C#] 문자열의 응용 (0) | 2023.07.07 |
[C#] 클래스의 응용 (0) | 2023.07.06 |
[C#] 클래스의 응용 (0) | 2023.07.05 |