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