如何读取具有固定字符串元素的结构文件? [英] How can read file with structure contains fixed string element?

查看:148
本文介绍了如何读取具有固定字符串元素的结构文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好.
我正在尝试读取具有包含固定字符串元素的结构的二进制文件.但这行不通.
我知道具有以下结构的dat文件. DAT文件是由其他应用程序创建的,可以使用Perl或VB 6或任何语言进行编码.

FILE.DAT

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.

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;
        }


将dat文件加载到Datatable方法.


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;

       }


读取文件时标志字段具有"值时出现问题.
如果我用vb6做到了,它就可以正常工作.
标志字段的值是"S","M","T" ...

帮我修复此代码.
非常感谢


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

推荐答案

我会考虑使用 FileHelpers [ ^ ]读取文件
I would consider using FileHelpers[^] to read the file


这篇关于如何读取具有固定字符串元素的结构文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆