栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

AC#等效于C的读取文件I / O

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

AC#等效于C的读取文件I / O

使用P /
Invoke编组器没有任何问题,这也不是不安全的,并且您不必使用unsafe关键字。弄错它只会产生错误的数据。与显式编写反序列化代码相比,使用起来容易得多,尤其是在文件包含字符串的情况下。您不能使用BinaryReader.ReadString(),它假定字符串是由BinaryWriter编写的。但是,请确保使用struct声明声明数据的结构,this.GetType()不太可能正常工作。

这是一个通用类,可用于任何结构声明:

  class StructureReader<T> where T : struct {    private byte[] mBuffer;    public StructureReader() {      mBuffer = new byte[Marshal.SizeOf(typeof(T))];    }    public T Read(System.IO.FileStream fs) {      int bytes = fs.Read(mBuffer, 0, mBuffer.Length);      if (bytes == 0) throw new InvalidOperationException("End-of-file reached");      if (bytes != mBuffer.Length) throw new ArgumentException("File contains bad data");      T retval;      GCHandle hdl = GCHandle.Alloc(mBuffer, GCHandleType.Pinned);      try {        retval = (T)Marshal.PtrToStructure(hdl.AddrOfPinnedObject(), typeof(T));      }      finally {        hdl.Free();      }      return retval;    }

文件中数据结构的示例声明:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]struct Sample {  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 42)]  public string someString;}

您需要调整结构声明和属性,以与文件中的数据匹配。读取文件的示例代码:

  var data = new List<Sample>();  var reader = new StructureReader<Sample>();  using (var stream = new FileStream(@"c:temptest.bin", FileMode.Open, FileAccess.Read)) {    while(stream.Position < stream.Length) {      data.Add(reader.Read(stream));    }  }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/506750.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号