System.IO.Ports.SerialPort.ReadTo C# (CSharp) Méthode

ReadTo() public méthode

public ReadTo ( string value ) : string
value string
Résultat string
		public string ReadTo (string value)
		{
			CheckOpen ();
			if (value == null)
				throw new ArgumentNullException ("value");
			if (value.Length == 0)
				throw new ArgumentException ("value");

			// Turn into byte array, so we can compare
			byte [] byte_value = encoding.GetBytes (value);
			int current = 0;
			List<byte> seen = new List<byte> ();

			while (true){
				int n = read_byte ();
				if (n == -1)
					break;
				seen.Add ((byte)n);
				if (n == byte_value [current]){
					current++;
					if (current == byte_value.Length)
						return encoding.GetString (seen.ToArray (), 0, seen.Count - byte_value.Length);
				} else {
					current = (byte_value [0] == n) ? 1 : 0;
				}
			}
			return encoding.GetString (seen.ToArray ());
		}

Usage Example

Exemple #1
0
        /// <summary>
        /// Read PLC via SerialPort
        /// </summary>
        /// <param name="PlcPort">Serial Port address</param>
        /// <returns></returns>
        public static string ReadPLC(System.IO.Ports.SerialPort PlcPort)
        {
            string FCS_rxd;
            string FCS  = "";
            string RXD  = "";
            string data = "";

            Stopwatch stopwatch = new Stopwatch();

            try
            {
                RXD  = "";
                data = "";
                PlcPort.ReadTimeout = 1000;
                RXD = PlcPort.ReadTo("\r");
            }
            catch (Exception)
            {
                return(null);
            }

            FCS_rxd = RXD.Substring(RXD.Length - 3, 2);
            if (RXD.Substring(0, 1) == "@" && RXD.Length > 3) //response has data
            {
                RXD = RXD.Substring(0, RXD.Length - 3);
            }

            /*else if (RXD.Substring(0, 1) == "@" && RXD.Length == 11)//reponse has no data but error
             * {
             *  MessageBox.Show("PLC comm error");
             *  return data;
             * }*/
            else if (RXD == "")
            {
                return(null);
            }

            FCS = GetFCS(RXD);
            if (FCS == FCS_rxd)
            {
                data = RXD.Substring(23, RXD.Length - 23);
                return(data);
            }
            else
            {
                return(null);
            }
        }
All Usage Examples Of System.IO.Ports.SerialPort::ReadTo