C\#바 이 너 리 파일 을 읽 고 쓰 는 방법

전체 코드 는 다음 과 같 습 니 다.네 임 스페이스 도입:

using System.IO; 
전체 코드:

namespace BinaryStreamApp 

    class Program 
    { 
        static void Main(string[] args) 
        { 
            //  
            FileStream fs; 
            fs = new FileStream("C:\\BinFile.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite); 
            BinaryWriter bw = new BinaryWriter(fs); 
            //  
            double aDouble = 1234.56; 
            int aInt = 34567; 
            char[] aCharArray = { 'A', 'B', 'C' }; 
            // Write  
            bw.Write(aDouble); 
            bw.Write(aInt); 
            bw.Write(aCharArray); 
            int length = Convert.ToInt32(bw.BaseStream.Length); 
            fs.Close(); 
            bw.Close(); 
            //  
            fs = new FileStream("C:\\BinFile.dat", FileMode.OpenOrCreate, FileAccess.Read); 
            BinaryReader br = new BinaryReader(fs); 
            Console.WriteLine(br.ReadDouble().ToString()); 
            Console.WriteLine(br.ReadInt32().ToString()); 
            char[] data = https://www.jb51.net/andrew-blog/archive/2011/12/02/br.ReadChars(length); 
            for (int i = 0; i < data.Length; i++) 
            { 
                Console.WriteLine("{0,7:x}",data[i]); 
            } 
            fs.Close(); 
            br.Close(); 
            Console.ReadLine(); 
        } 
    } 

운행 효과:

이 예 에서 Binary Writer 대상 의 Write 방법 을 사용 하여 파일 에 Double 형식의 변수 aDouble 을 기록 할 때 매개 변 수 는 Double 형식 이기 때문에 Write(Double)의 리 셋 형식 을 호출 하여 파일 흐름 에 8 바이트 길이 의 부동 소수점 형식 데 이 터 를 기록 합 니 다.이에 대응 하여 이 데 이 터 를 읽 을 때 ReadDouble()방법 으로 현재 흐름 에서 8 바이트 부동 소수점 값 을 읽 습 니 다. Int 32 형식의 변수 aInt 를 쓸 때 시스템 은 Write(Int 32)방법 을 자동 으로 호출 하여 파일 흐름 에 4 바이트 에 기호 정수 가 있 고 데 이 터 를 읽 을 때 ReadInt 32()방법 을 호출 하여 파일 흐름 에서 4 바이트 길이 의 데 이 터 를 읽 습 니 다.이 를 통 해 알 수 있 듯 이 Binary Reader 와 Binary Writer 대상 은 흐름 에 정형,부동 소수점 등 고정된 길이 의 데 이 터 를 기록 하고 읽 을 때 매우 편리 하 다.

좋은 웹페이지 즐겨찾기