[StructLayout(LayoutKind.Sequential)]//Sim 卡记录的数据结构
public struct SimRecord
{
public IntPtr cbSize;
public IntPtr dwParams;
public IntPtr dwRecordType;
public IntPtr dwItemCount;
public IntPtr dwSize;
}
public static string GetSimIMSI()
{
//获取Sim卡的ICCID
IntPtr res, hSim;
//初始化Sim卡列表
res = SimInitialize(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, out hSim);
if (res != IntPtr.Zero)
return "-1"; //Can not Initialize Sim.
SimRecord rec = new SimRecord();
rec.cbSize = (IntPtr)Marshal.SizeOf(rec);
res = SimGetRecordInfo(hSim, (IntPtr)EF_ICCID, ref rec);//获取ICCID的数据结构信息
if (res != IntPtr.Zero)
return "-2"; //Could not read the ICCID information from the SIM..
byte[] bData = new byte[(int)rec.dwSize + 1];//这里多加了一个字节来扩充一下缓冲区
IntPtr dwBytesRead = IntPtr.Zero;
res = SimReadRecord(hSim, (IntPtr)EF_ICCID, rec.dwRecordType, IntPtr.Zero, bData, (IntPtr)bData.Length, ref dwBytesRead);
if (res != IntPtr.Zero)
return "-3"; //Could not read the ICCID from the SIM.
SimDeinitialize(hSim);
string str = byteToString(bData);
return str;
}
public static string byteToString(byte[] b)
{
StringBuilder sb = new StringBuilder();
int n = b.Length;
for (int i = 0; i < n; i++)
{
sb.Append(StrReverse(b[i].ToString("x").PadLeft(2, '0')));
}
return sb.ToString().Substring(0, 20);
}
public static string StrReverse(string str) //高低位转换
{
StringBuilder sb = new StringBuilder();
sb.Append(str[1]);
sb.Append(str[0]);
return sb.ToString();
}
#endregion