본문 바로가기
전공/C# 프로그래밍

12강. 파일 다루기 (1)

by 임 낭 만 2023. 6. 3.

파일 입출력

파일과 디렉터리 정보 관리

  • 파일은 컴퓨터 저장 매체에 기록되는 데이터의 묶음
  • 디렉터리는 파일이 위치하는 주소이고 파일을 담는 폴더라고 불림
  • .NET은 System.IO 네임스페이스 안에 다음의 클래스를 제공

주요 메소드와 프로퍼티

  • File, FileInfo, Directory, DirectoryInfo 클래스가 제공하는 메소드와 프로퍼티
    • 파일/디렉터리의 생성, 복사, 삭제, 이동, 정보 조회 등의 기능을 수행

디렉터리 / 파일 정보 조회 예제 코드

//디렉토리/파일 정보 조회하기
//매개 변수를 입력하지 않으면 현재 디렉토리 조회
//매개변수 입력하면, 입력한 디렉토리 조회
using System;
using System.Linq;
using System.IO;

namespace Dir
{
    class MainApp
    {
        static void Main(string[] args)
        {
            string directory;
            if (args.Length < 1)
                directory = ".";
            else
                directory = args[0];

            Console.WriteLine($"{directory} directory Info");
            Console.WriteLine("- Directories :");
            
            //하위 디렉터리 목록 조회
            var directories = (from dir in Directory.GetDirectories(directory)
                         let info = new DirectoryInfo(dir)
                         select new
                         {
                             Name = info.Name,
                             Attributes = info.Attributes
                         }).ToList();
            foreach (var d in directories)
                Console.WriteLine($"{d.Name} : {d.Attributes}");
            //하위 파일 목록 조회
            Console.WriteLine("- Files :");
            var files = (from file in Directory.GetFiles(directory)
                         let info = new FileInfo(file)	//let은 LINQ안에서 변수를 만듦. LINQ의 var
                              select new
                              {
                                  Name = info.Name,
                                  FileSize = info.Length,
                                  Attributes = info.Attributes
                              }).ToList();
            foreach (var f in files)
                Console.WriteLine($"{f.Name} : {f.FileSize}, {f.Attributes}");
        }
    }
}

System.IO.Stream 클래스 

  • 스트림 (Stream)
    • 데이터가 흐르는 통로를 의미
    • 저장매체(하드디스크)와 메모리 사이의 스트림을 놓은 후 파일에 담긴 데이터를 바이트 단위로 메모리로 차례차례 옮김
    • 파일을 처음부터 끝까지 순서대로 읽고 쓰는 “순차접근” 가능
    • 또한, 곧장 원하는 주소에 위치한 데이터에 접근하는 “임의접근” 가능
  • .NET 에서 제공하는 Stream 클래스
    • 추상 클래스 형태로 인스턴스를 만들기 위해 파생클래스를 이용
    • 하나의 스트림 모델로 다양한 매체나 장치들에 대한 파일 입출력을 다룰 수 있음
    • 주요 파생클래스
      • FileStream : 디스크 파일에 데이터를 기록
      • NetworkStream : 네트워크를 통해 데이터를 주고받도록 지원
      • BufferdStream : 데이터를 메모리 버퍼에 담았다가 일정량이 쌓일 때마다 기록

FileStream 클래스 : 파일 쓰기

  • FileStream 클래스의 인스턴스 생성

  • 파일에 데이터를 기록하기 위해 Stream 클래스로 부터 물려받은 메소드
    • Write( )와 WriteByte( ) 메소드는 매개변수로 byte 또는 byte 배열만 입력 받음

  • BitConverter 클래스
    • 임의 형식의 데이터를 byte의 배열로 변환
    • byte의 배열에 담겨있는 데이터를 다시 임의 형식으로 변환
    • 예를 들어, long 형식의 데이터를 파일에 기록

FileStream 클래스 : 파일 읽기

  • 파일에서 데이터를 읽기 위해 Stream 클래스로 부터 물려받은 두 개의 메소드

using System;
using System.IO;

namespace BasicIO
{
    class MainApp
    {
        static void Main(string[] args)
        {
            long someValue = 0x123456789ABCDEF0;
            //X16에서 X는 수를 16진수로 표현하고 뒤의 숫자 16은 열여섯 자리 수로 표현
            Console.WriteLine("{0,-1} : 0x{1:X16}", "Original Data", someValue);

            Stream outStream = new FileStream("a.dat", FileMode.Create);
            byte[] wBytes = BitConverter.GetBytes(someValue);
            Console.Write("{0,-13} : ", "Byte array");

            foreach (byte b in wBytes)
                Console.Write("{0:X2} ", b);
            Console.WriteLine();

            outStream.Write(wBytes, 0, wBytes.Length);
            outStream.Close();
            
            byte[] rbytes = new byte[8];

            Stream inStream = new FileStream("a.dat", FileMode.Open);
            inStream.Read(rBytes, 0, rBytes.Length);
            
            long readValue = BitConverter.ToInt64(rbytes, 0);
            Console.WriteLine("{0,-13} : 0x{1:X16} ", "Read Data", readValue);
            inStream.Close();
        }
    }
}

댓글