2014-01-16 39 views
1

我知道有關於c#串口接收和寫入的問題,但我沒有找到有用的解決方案在我的情況。我已經在c#windows應用程序中編寫了一個小程序。這個應用程序讓用戶登錄與移動miscall。我無法提取從串口收到的數據。我想從輸出中提取手機號碼,但沒有運氣。貝婁是我的代碼,請告訴我如何從輸出中提取手機號碼並將其顯示在密碼字段中。謝謝串口數據陣列提取

SerialPort port = new SerialPort("COM5", 9600, Parity.None, 8, StopBits.One); 
    private void Login_Load(object sender, EventArgs e) 
    { 
     port.RtsEnable = true; 
     port.DtrEnable = true; 
     port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); 
     if (!port.IsOpen) port.Open(); 
     port.Write("AT+CLIP=1" + Environment.NewLine); 
    } 

    delegate void SetTextCallback(string text); 

    private void SetText(string text) 
    { 
     // InvokeRequired required compares the thread ID of the 
     // calling thread to the thread ID of the creating thread. 
     // If these threads are different, it returns true. 
     if (this.txtPassword.InvokeRequired) 
     { 
      SetTextCallback d = new SetTextCallback(SetText); 
      this.Invoke(d, new object[] { text }); 
     } 
     else 
     { 
      this.txtPassword.Text = text; 
     } 
    } 

    protected void port_DataReceived(object sender, SerialDataReceivedEventArgs e) 
    { 
     var currentPort = (SerialPort)sender; 
     string result = currentPort.ReadExisting(); 
     MessageBox.Show(result); 
     //if (!result.Contains("\r\nRING\r\n")) return; 
     //currentPort.Write("AT+CHUP" + Environment.NewLine); 
     //txtPassword.Text = result.Split('\"')[1]; 
     //SetText(result.Split('\"')[1]); 
     //port.Write("AT+CHUP" + Environment.NewLine); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     LoginUser(); 
    } 

從港口收到的數據如下。我想從中提取手機號碼。我是新手,在C#:

 
RING 
+CLIP: "032232323423",161,"",0,"",0 

當我嘗試打印驗證碼的setText(result.Split( '\'「)[1]); 它給我的錯誤[索引超出區間震盪]

在DataReceived事件檢索
+0

使用ReadLine()而不是ReadExisting()。 –

+0

由於字符串中沒有'\'字符,因此您將索引超出範圍。 –

+0

我試過ReadLine()而不是ReadExisting,但沒有運氣。請任何其他想法? – user3156937

回答

0

,你可以這樣寫:反正

byte[] buffer = new buffer[1024]; 
int readBytes = port.Read(buffer, 0, port.BytesToRead); 

,我認爲你可以得到這樣的電話號碼:

int firstMark = result.IndexOf('\"'); 
result.SubString(firstMark, result.IndexOf('\"', firstMark + 1) - firstMark);