添加重要的命名空间:

using System.Runtime.InteropServices;

先建立结构相同(char长度相同)的Struct类型用于转换:

[StructLayout(LayoutKind.Sequential, Pack = )]
public struct Employee
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = )]
public char[] EmployeeId;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = )]
public char[] LastName;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = )]
public char[] FirstName;
//这里省略很多列
}

数据文本类似下面, 如这三列固定长度(6,30,30):

10001 Nick                          Yang
10002 Nick2 Yang
10003 Nick3 Yang

代码获取并转换:

        /// <summary>
/// Get data from interface file
/// </summary>
public void GetDataFromFile()
{
try
{
string path = ConfigurationManager.ConnectionStrings["DataPath"].ConnectionString;
if (File.Exists(path))
{
string[] rows = File.ReadAllLines(path, Encoding.UTF8);
foreach (string row in rows)
{
byte[] bytes = Encoding.UTF8.GetBytes(row);
//以下为重点代码
int size = Marshal.SizeOf(typeof(Employee));
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.Copy(bytes, , buffer, size);
//此处已经完成转换
Employee emp = (Employee)Marshal.PtrToStructure(buffer, typeof(Employee)); //省略很多代码
}
catch (Exception ex)
{
throw new Exception("Error when Copying bytes from interface to Employee", ex);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
}
else
{
throw new Exception(string.Format("Error. Can`t not find the interface file at '{0}'", path));
} }
catch (Exception ex)
{
throw new Exception("Error when getting data from interface file.", ex);
}
}

最新文章

  1. MATLAB 图像操作基础
  2. PHP使用libevent实现高性能httpServer
  3. 50.ISE布局布线错误
  4. zoj Simple Equation 数论
  5. hive 使用脚本清洗数据:时间戳转日期
  6. Sublime text 添加lua
  7. 我一个二本大学是如何拿到百度、网易大厂offer的!
  8. 让pip使用python3而不是python2
  9. ORA-08176 错误的一个案例
  10. qt5程序打包含qml
  11. JumpServer 安装配置
  12. 转 jQuery中的$.extend方法来扩展JSON对象
  13. php5.4后htmlspecialchars输出为空的问题
  14. Docker Compose 一键部署Nginx代理Tomcat集群
  15. Pillow《转载》
  16. Linux下的二进制兼容性的检测
  17. CTF之PHP黑魔法总结
  18. 福大软工1816 &#183; 评分结果 &#183; Alpha冲刺
  19. BarcodeLib -- 一个精简而不失优雅的条形码生成库
  20. C#语言-03.逻辑控制语句

热门文章

  1. 8. 冒泡法排序和快速排序(基于openCV)
  2. Microsoft Visual C++ 不支持long long
  3. 21. DNS 配置和端口检测
  4. 网络基础知识HTTP(1) --转载
  5. jquery列表动画
  6. Autofac创建实例的方法总结 【转】
  7. POJ 2140 Herd Sums
  8. oracle中anyData数据类型的使用实例
  9. &#39;data-&#39;属性的作用是什么?
  10. getHibernateTemplate().find方法详解