2011-03-28 6 views
2

이진 파일이 있습니다. C#을 사용하여이 이진 파일을 읽는 방법에 대한 단서가 없습니다.C#을 사용하여 이진 파일을 읽는 방법?

바이너리 파일의 레코드의 정의 C++에 설명은 다음과 같습니다

#define SIZEOF_FILE(10*1024) 
//Size of 1234.dat file is: 10480 + 32 byte (32 = size of file header) 
typedef struct FileRecord 
{ 
WCHAR ID[56]; 
WCHAR Name[56]; 
int Gender; 
float Height; 
WCHAR Telephne[56]; 
and........ 
} 

어떻게 C#에서 레코드를 포함하는 바이너리 파일을 읽습니까하고 편집 한 후 다시 쓰기?

+0

게시 한 코드는 C 나 C++와 유사합니다. C#에는'typedef '가 없습니다. –

+2

@ 존 : OP가 그가 알고있는 언어로 파일을 설명하고 있기 때문에 C#으로 파일을 열 수 있도록 도와 줄 수 있다고 생각합니다. –

+0

파일 구조를 알고 있다고 생각합니까? 그렇지 않으면 내용 해석에 어려움을 겪을 것입니다. – Tony

답변

5

실제 매핑이지만 파일을 찾지 않고 무엇을 다시 읽는지 확인하는 것이 중요합니다.)

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)] 
public struct FileRecord 
{ 
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 56)] 
    public char[] ID; 
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 56)] 
    public char[] Name; 
    public int Gender; 
    public float height; 
    //... 
} 

class Program 
{ 
    protected static T ReadStruct<T>(Stream stream) 
    { 
     byte[] buffer = new byte[Marshal.SizeOf(typeof(T))]; 
     stream.Read(buffer, 0, Marshal.SizeOf(typeof(T))); 
     GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); 
     T typedStruct = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); 
     handle.Free(); 
     return typedStruct; 
    } 

    static void Main(string[] args) 
    { 
     using (Stream stream = new FileStream(@"test.bin", FileMode.Open, FileAccess.Read)) 
     { 
      FileRecord fileRecord = ReadStruct<FileRecord>(stream); 
     } 
    } 
+0

+1 ... "파일을 읽음으로써 얻은 결과를 확인하십시오."어떻게할까요? 즉 무엇을 찾고 있습니까? 저는 바이너리 데이터로 작업 할 때 완전한 초보자입니다. –

+0

파일에서 이진 데이터의 레이아웃, 즉 레코드 크기는 무엇인지, 각 레코드의 필드는 무엇이며 그 크기는 무엇인지 알아야합니다. – BrokenGlass

0

당신은 파일을 읽을 FileStream을 사용할 수 있습니다 - 파일을 열 File.Open 방법을 사용하고 FileStream을 얻을 - 더 details

4

여기를 보면 아래의 샘플을 참조하십시오. 도움이

public byte[] ReadByteArrayFromFile(string fileName) 
{ 
    byte[] buff = null; 
    FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); 
    BinaryReader br = new BinaryReader(fs); 
    long numBytes = new FileInfo(fileName).Length; 
    buff = br.ReadBytes((int)numBytes); 
    return buff; 
} 

희망 ...

내가 테스트하지 않았습니다 직접 바이너리 파일의 데이터의 구조에 매핑되는 struct 유형과 StructLayout를 (사용하여이 일을 더 좋은 방법은 실제로있다
관련 문제