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"); } }