C#文件流写入结构体
来源:互联网 发布:c语言 char负值 编辑:程序博客网 时间:2024/06/06 03:37
1、定义结构体
namespace WindowsFormsApplication1
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct fsnHead
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public UInt16[] HeadStart;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public UInt16[] HeadString;
public UInt32 Counter;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public UInt16[] HeadEnd;
}
}
2、在方法里处理
private void button1_Click(object sender, EventArgs e)
{
string strFile = Application.StartupPath + "\\Data.dat";
FileStream fs = new FileStream(strFile, FileMode.Open, FileAccess.ReadWrite);
StreamReader sr = new StreamReader(fs);
fsnHead fsnHeader = new fsnHead();
int headSize = Marshal.SizeOf(typeof(fsnHead));
byte[] tempReader = new byte[headSize];
fs.Seek(0, SeekOrigin.Begin);
fs.Read(tempReader, 0, headSize);
fsnHeader = (fsnHead)BytesToStuct(tempReader, typeof(fsnHead));
}
public static object BytesToStuct(byte[] bytes, Type type)
{
//得到结构体的大小
int size = Marshal.SizeOf(type);
//byte数组长度小于结构体的大小
if (size > bytes.Length)
{
//返回空
return null;
}
//分配结构体大小的内存空间
IntPtr structPtr = Marshal.AllocHGlobal(size);
//将byte数组拷到分配好的内存空间
Marshal.Copy(bytes, 0, structPtr, size);
//将内存空间转换为目标结构体
object obj = Marshal.PtrToStructure(structPtr, type);
//释放内存空间
Marshal.FreeHGlobal(structPtr);
//返回结构体
return obj;
}
- C#文件流写入结构体
- C#下面,怎么把一个自定义的结构体写入到文件中去?
- 结构体写入文件(二进制)
- 结构体 写入文件 C++ 深入理解
- C语言中将结构体写入文件
- c++结构体写入文件实例
- C语言中将结构体写入文件
- C语言中将结构体写入文件
- iOS基础知识:文件流写入读取结构体变量、数组、结构体数组
- C# 读取写入文件
- C# 文件写入
- C# 写入txt 文件
- C#文件写入操作
- C#文件写入
- C# 写入xml文件
- c# 文件写入
- c#写入文件读出文件
- 将结构体按位写入文件
- SQL语句简单整理
- Redis常用数据类型
- Google Earth与ArcGIS数据交互(四)
- 开通新博客,记录新生活
- 解决Qt中文乱码问题
- C#文件流写入结构体
- oracle rank排序
- 获取mp4文件信息3 - 计算电影声音采样频率
- 网络游戏通信协议
- system_server运行机制
- poj 3940 Grey Area 浮点输出控制
- python7:字符串
- Linux下Bluez的编程实现
- Shell编程之多行注释