본문 바로가기

프로그래밍/C,C++

[C#] 파일 읽고,쓰기 기초

> File

static File.Create - 파일 생성

static File.Copy - 파일 복사

static File.Delete - 파일 삭제

static File.Exists - 파일 유무 검사

static File.Open - FileStream 열기

static File.OpenRead - FileStream 읽기 전용으로 열기

static File.OpenWrite - FileStream 쓰기 전용으로 열기

static File.OpenText - UTF8 형식의 StreamReader 열기

static File.ReadAllLines - string[] 으로 모든 줄을 읽고, 닫음.

static File.ReadLines - IEnumerable<string>으로 각 라인을 읽음

static File.ReadAllBytes - byte[] 으로 모드 바이트 읽고, 닫음.

static File.WriteAllBytes

static File.WriteAllLines

.

.

 

 

> text 파일에서 읽기/쓰기

System.IO.TextWriter

System.IO.TextReader

이 클래스들은 추상 클래스이므로, 실제 생성시는 이를 상속받은 클래스 사용

 

System.IO.TextWriter

  System.IO.StreamWriter

    System.IO.StringWriter

      System.WEB.HttpWriter

 

System.IO.TextReader

  System.IO.StreamReader

    System.IO.StringReader

      System.WEB.HttpReader

 

 

ex)

TextWriter tw = StreamWriter("텍스트 파일명");

tw.WriteLine( string 문자열 );

tw.Write( value );

tw.Close();

 

> 특정 인코딩 text 

System.Text.Encoding

 

ex)

StreamReader sr= new StreamReader("텍스트 파일명", Encoding.UTF8 );

string line = sr.ReadLine();

sr.Close();

 

 

> 바이너리 파일 읽기/쓰기

System.IO.FileStream

System.IO.BinaryReader

System.IO.BinaryWriter

 

ex )

FileStream fs = new FileStream( "파일명", FileMode.CreateNew, FileAccess.Write );

BinaryWriter bw = new BinaryWriter( fs );

 

bw.Write( value );

 

bw.Close();

fs.Close();

 

 

> 관리된(?) or 고정된 구조체를 파일에 읽기/쓰기

System.Runtime.InteropServices.Marshal

Marshal.PtrToStructure : 구조체로 마샬링

Marshal.StructureToPtr : 포인터로 마샬링

 

 

C#은 c/c++과 다른 string 타입등이 존재 하므로, 

소켓 전송이나 파일헤더 등의 바이너리 저장의 경우 구조체의 크기를 정확히 지정해 주어야 한다.

 

StructureLayout : 구조체 구조 ( LayoutKind.종류, CharSet=캐릭터셋, Pack = 패킹 바이트 크기)

LayoutKind.Sequential : 순서대로 패킹

LayoutKind.Explicit : 옵셋에 따라 패킹

string의 경우 CharSet.Unicode 이면 각 2byte, CharSet을 지정하지 않으면 1byte로 처리.

 

FieldOffset : 구조체 종류가 LayoutKind.Explicit인 경우 명확한 위치를 지정.

MarshalAs : 어떤 타입으로 마샬링 할지 정의

UnmanagedType

   ByValTStr : 고정길이 문자배열, SizeConst 길이 지정.

   LPStr : null 끝나는 ansi 문자배열의 포인터

   LPWStr : null 끝나는 유니코드 문자배열의 포인터

 

[StructureLayout(LayoutKind.Explicit , Pack=1)]

struct MyStruct

{

    [FieldOffset(0)]

    [MarshalAs( UnmanagedType.ByValTStr, SizeConst = 128) ]

    public string name;

 

    [FiledOffset(128)]

    [MarshalAs( UnmanagedType.ByValTStr, SizeConst = 16) ]

    public string type;

 

    [FiledOffset(144)]

    public int num;

 

    [FieldOffset(148)]

    [MarshalAs( UnmanagedType.ByValArray, SizeConst = 32) ]

    public byte[] value;

};

 

ex) 위 구조체를 사용해 바이너리 파일 읽고, 쓰기

MyStruct data;

int size = Marshal.SizeOf( typeof( MyStruct ) );

byte[] buffer = new byte[size];

 

// 파일 내용을 byte 버퍼로 읽기

FileStream fs = new FileStream("파일명", FileMode.Open, FileAccess.Read );

BinaryReader br = new BinaryReader( fs );

buffer = br.readBytes( size );

br.Close();

 

// byte 버퍼를 구조체에 쓰기

GCHandle handle = GCHandle.Alloc( buffer, GCHandleType.Pinned );

data = (MyStruct) Marshal.PtrToStructure( handle.AddrOfPinnedObject(), typeof( MyStruct) );

handle.Free();

 

// 쓰기.. 읽기의 역순 -_-;;

// 구조체 내용을 byte 버퍼로 가져오기

GCHandle handle = GCHandle.Alloc( buffer, GCHandleType.Pinned);

Marshal.StructureToPtr( data, handle.AddrOfPinnedObject(), false);

 

// byte 버퍼내용을 파일로 쓰기

BinaryWriter bw = new BinaryWriter( bs );

bw.writeBytes( buffer );

bw.Close();

'프로그래밍 > C,C++' 카테고리의 다른 글

Boost 라이브러리 빌드  (0) 2018.08.28
[Win API] Console project  (0) 2017.12.06
[C++] 시스템 클럭 밀리세컨드 얻기  (0) 2017.12.06
Kinect sdk 이미지 얻기  (0) 2017.10.26
C# OLEDB 엑셀 읽기  (0) 2016.02.21
[C#] 이미지 처리 기본 사항들  (0) 2013.09.12
[C#] 이벤트  (0) 2013.09.12
[C#] 폼 띄우기  (0) 2013.09.12
GCC 옵션  (0) 2011.07.21
POSIX 쓰레드 함수들  (0) 2010.04.16