Click here to Skip to main content
15,900,589 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all.
I am trying to read a binary file with a structure that contain fixed string element. But it doesn't work fine.
I know dat file with structure as below. The DAT file was created by other application that could code by Perl or VB 6 or any language.

FILE.DAT
ID Int (2 Byte)
Name String (36) 
Double Count
Flag String(1)

Here is my code.

C#
public struct sFile
        {
            public short ID;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst=36)]
            public string Name;
            [MarshalAs(UnmanagedType.R8)]
            public double Count;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)]
            public string Flag;
        }

Load dat file to Datatable Method.
public DataTable sFileLoad(string pztablename, string pzfilename)
       {
           sFile iFile = new sFile ();
           DataTable dtt = new DataTable();
           if (sfRead == null) OpenSFile(pzfilename);
           if (sfRead.EOF) OpensFile(pzfilename); // Open dat file method.

           dtt.Columns.AddRange(new DataColumn[] {
               new DataColumn("ID", typeof(Int16)),
               new DataColumn("Name", typeof(String)),
               new DataColumn("Count", typeof(decimal)),
               new DataColumn("Flag", typeof(String)))
               });
           try
           {
               while (!sfRead.EOF)
               {
                   sFile = (sFile)sfRead.GetNextStructureValue();

                   dtt.Rows.Add(iFile.ID,
                                iFile.Name,
                                iFile.Count,
                                iFile.Flag);

               }


           }
           catch (Exception Ex)
           {
               MessageBox.Show(Ex.Message.ToString());
           }

           return dtt;

       }

There is a problem while reading file is the flag field have "" value.
if I did it with vb6 it works fine.
Value of Flag field is "S", "M", "T"...

Help me fix this code.
Many thanks
Posted
Updated 19-May-10 22:23pm
v2

1 solution

I would consider using FileHelpers[^] to read the file
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900