2010-09-03

C# firestream 讀檔、struct 和 byte 之間的轉換

using System.IO;
using System.Runtime.InteropServices;
using System;
 
//1. 把檔案讀成 Byte 形式
private byte[] readFile(string strFileName)
{
 
    byte[] buffer = null;
    FileStream fs = new FileStream(strFileName, FileMode.Open, FileAccess.Read);
    try
    {
        BinaryReader br = new BinaryReader(fs);
        int len = System.Convert.ToInt32(fs.Length);
 
        buffer = br.ReadBytes(len);
 
    }
    finally
    {
        fs.Close();
    }
    return buffer;
}
 
//2. struct 轉成 byte
static byte[] StructToBytes(object structObj)
{
    int size = Marshal.SizeOf(structObj);
    IntPtr buffer = Marshal.AllocHGlobal(size);
    try
    {
        Marshal.StructureToPtr(structObj, buffer, false);
        byte[] bytes = new byte[size];
        Marshal.Copy(buffer, bytes, 0, size);
        return bytes;
    }
    finally
    {
        Marshal.FreeHGlobal(buffer);
    }
}
 
//3. byte 轉成 struct
static object BytesToStruct(byte[] bytes, Type strcutType)
{
    int size = Marshal.SizeOf(strcutType);
    IntPtr buffer = Marshal.AllocHGlobal(size);
    try
    {
        Marshal.Copy(bytes, 0, buffer, size);
        return Marshal.PtrToStructure(buffer, strcutType);
    }
    finally
    {
        Marshal.FreeHGlobal(buffer);
    }
}

0 意見 :

張貼留言