/// <summary> /// 按序号读取短信 /// </summary> /// <param name="index">序号</param> /// <returns>信息字符串 (中心号码,手机号码,发送时间,短信内容)</returns> public string ReadMsgByIndex(int index) { string temp = string.Empty; string msgCenter, phone, msg, time; PDUEncoding pe = new PDUEncoding(); try { temp = SendAT("AT+CMGR=" + index.ToString()); } catch (Exception ex) { throw ex; } if (temp.Trim() == "ERROR") { throw new Exception("没有此短信"); } temp = temp.Split((char)(13))[3]; //取出PDU串(char)(13)为0x0a即\r 按\r分为多个字符串 第3个是PDU串 pe.PDUDecoder(temp, out msgCenter, out phone, out msg, out time); if (AutoDelMsg)//如果阅读完短信自动删除设置为真 { try { DelMsgByIndex(index); } catch { } } return(msgCenter + "," + phone + "," + time + "," + msg); }
/// <summary> /// 发送短信 (重载) /// </summary> /// <param name="phone">手机号码</param> /// <param name="msg">短信内容</param> /// <param name="msgType">短信类型</param> public void SendMsg(string phone, string msg, MsgType msgType) { if (msgType == MsgType.AUSC2) { SendMsg(phone, msg); } else { PDUEncoding pe = new PDUEncoding(); pe.ServiceCenterAddress = msgCenter; //短信中心号码 服务中心地址 string temp = pe.PDU7BitEncoder(phone, msg); int len = (temp.Length - Convert.ToInt32(temp.Substring(0, 2), 16) * 2 - 2) / 2; //计算长度 try { temp = SendAT("AT+CMGS=" + len.ToString() + "\r" + temp + (char)(26)); //26 Ctrl+Z ascii码 } catch (Exception) { throw new Exception("短信发送失败"); } if (temp.Substring(temp.Length - 4, 3).Trim() == "OK") { return; } throw new Exception("短信发送失败"); } }
/// <summary> /// 按序号读取短信 /// </summary> /// <param name="index">序号</param> /// <param name="msgCenter">短信中心</param> /// <param name="phone">发送方手机号码</param> /// <param name="msg">短信内容</param> /// <param name="time">时间字符串</param> public void ReadMsgByIndex(int index, out string msgCenter, out string phone, out string msg, out string time) { string temp = string.Empty; PDUEncoding pe = new PDUEncoding(); try { temp = SendAT("AT+CMGR=" + index.ToString() + "\r"); } catch (Exception ex) { throw ex; } if (temp.Trim() == "ERROR") { throw new Exception("没有此短信"); } temp = temp.Split((char)(13))[2]; //取出PDU串(char)(13)为0x0a即\r 按\r分为多个字符串 第3个是PDU串 pe.PDUDecoder(temp, out msgCenter, out phone, out msg, out time); }
/// <summary> /// 获取所有信息 /// </summary> /// <returns></returns> public string[] GetAllMsg() { string[] result = new string[255];//存储255条短信,一般手机上面存储的短信少于这个数 string[] temp = null; string tt = string.Empty; tt = this.SendAT("AT+CMGL=4");//读取未读信息 if (tt.Substring(tt.Length - 4, 3).Trim() == "OK") { temp = tt.Split('\r'); } PDUEncoding pe = new PDUEncoding(); int i = 0;//计数 foreach (string str in temp) { if (str != null && str.Length != 0 && str.Substring(0, 2).Trim() != "+C" && str.Substring(0, 2) != "OK" && str.Substring(0, 2) != "AT") { result[i] = pe.PDUDecoder(str); i++; } } return(result); }