3 Replies - 3862 Views - Last Post: 16 October 2011 - 09:19 AM Rate Topic: ***** 1 Votes

#1 Writ-Z  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 03-October 11

[HELP]Read Structure From Binary File

Posted 12 October 2011 - 01:50 AM

Hello,
I am trying to decode a Binary File Since a Long Time......[Have tried about 1000 times with different codes]
I have the Following Structure Definition :

[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode, Pack = 1)]
public struct FHeader
{
[FieldOffset(0)]
public byte[]   FHead;
[FieldOffset(4)]
public byte     FHSize;
[FieldOffset(5)]
public byte     FReserved;
[FieldOffset(6)]
public UInt16   FFormat;
}



And Running The Code Like This :

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;
}
private void button_Click(object sender, EventArgs e)
{
    FileStream Fs = new FileStream(OutPutDir + @"\file.bin", FileMode.Open, FileAccess.Read);
    FHeader FileHeader = new FHeader();
    FileHeader = (FHeader)ReadStruct<FHeader>(Fs);
}



I am Getting AccessViolationException On this Line :

    T typedStruct = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));



Please Anyone Help Me.......

Where Am I Wrong?????

NOTE : I am Using a Writable and Readable File.....and I created the File just in the previous button click......and the File is in Closed State[Not Opened By any other Program]

Is This A Good Question/Topic? 0
  • +

Replies To: [HELP]Read Structure From Binary File

#2 Writ-Z  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 03-October 11

Re: [HELP]Read Structure From Binary File

Posted 16 October 2011 - 06:34 AM

So NONE CAN Help???
Still No Replies?????

40 Views???
Was This Post Helpful? 0
  • +
  • -

#3 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6053
  • View blog
  • Posts: 23,488
  • Joined: 23-August 08

Re: [HELP]Read Structure From Binary File

Posted 16 October 2011 - 07:40 AM

Have you tried debugging?
Was This Post Helpful? 0
  • +
  • -

#4 Writ-Z  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 03-October 11

Re: [HELP]Read Structure From Binary File

Posted 16 October 2011 - 09:19 AM

View PostJackOfAllTrades, on 16 October 2011 - 07:40 AM, said:

Have you tried debugging?



I dont Understand.....
[all are going correct except the AccessViolationException]

Here is the ScreenShot :
Posted Image

[Yes I Debugged the Code Also[Now]...
But Cant Find any Problem with the buffer sizes or handle allocation]
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1