public class SIM
{
#region 平臺呼叫
[DllImport("cellcore.dll")]
public extern static int SimInitialize(int dwFlags, IntPtr lpfnCallback, int dwParam, ref IntPtr lphSim);
[DllImport("cellcore.dll")]
public extern static int SimDeinitialize(IntPtr hSim);
[DllImport("cellcore.dll")]
public extern static int SimReadRecord(IntPtr hSim, int dwAddress, int dwRecordType, int dwIndex, byte[] lpData, int dwBufferSize, ref int dwSize);
int EF_ICCID = 0x2fe2;
int SIM_RECORDTYPE_TRANSPARENT = 1;
#endregion
//返回Sim卡背面的20位ICCID
public string SimSerialNumber()
{
IntPtr hSim = default(IntPtr);
byte[] iccid = new byte[10];
int dwsize = 0;
SimInitialize(0, IntPtr.Zero, 0, ref hSim);
SimReadRecord(hSim, EF_ICCID, SIM_RECORDTYPE_TRANSPARENT, 0, iccid, iccid.Length, ref dwsize);//在這裡獲取了SIM卡ID
SimDeinitialize(hSim);
return FormatAsSimString(iccid);
}
/// <summary>
/// 對SIM卡ID進行格式化
/// </summary>
/// <param name="iccid">byte格式的ID</param>
/// <returns>字串格式</returns>
private static string FormatAsSimString(byte[] iccid)
{
string rawString = GetRawIccIDString(iccid);
return String.Format("{0} {1} {2} {3}", rawString.Substring(0, 6), rawString.Substring(6, 5), rawString.Substring(11, 4), rawString.Substring(15, 4));
}
/// <summary>
/// 格式轉換函式
/// </summary>
/// <param name="iccid"></param>
/// <returns></returns>
private static string GetRawIccIDString(byte[] iccid)
{
System.Text.StringBuilder builder = new System.Text.StringBuilder();
int i = 0;
while (i < iccid.Length)
{
byte b = iccid;
builder.Append(ConvertInt4PairToString(b));
Math.Max(System.Threading.Interlocked.Increment(ref i), i - 1);
}
return builder.ToString();
}
private static string ConvertInt4PairToString(byte byteValue)
{
return ((byte)(byteValue << 4) | (byteValue >> 4)).ToString("x2");
}
}