0

I'm trying to read String data from TwinCAT PLC using WinForm and ADS.NET. I based my code from their sample codes. Writing the string into the console shows my data as: "123456????????????????????????". I can use a textbox and it will show and save "123456" but I want to save it directly without using textboxes.

What am I doing wrong? Or is there something missing from my code?

Thanks!

Additional info:

(I'm trying to save the data into a DB):

Error message

Code:

private String readPLCData(String variableHandle)
        {
            int length;
            string text;
            AdsStream dataStream;
            BinaryReader reader;
            try
            {
                varHandle = adsClient.CreateVariableHandle(variableHandle);
                // length of the stream = length of string in sps + 1
                dataStream = new AdsStream(31);
                reader = new BinaryReader(dataStream, System.Text.Encoding.ASCII);
                length = adsClient.Read(varHandle, dataStream);
                text = new string(reader.ReadChars(length));
                return text;
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
                return null;
            }
        }
  • I would guess these are non-printable chars. Try and output their values. – Fildor Nov 18 '19 at 08:42
  • 1
    You are missing the `/* Search for terminating zero character and cut at found position. Necessary if you want to compare the string to other strings */ text := text.Substring(0,text.IndexOf(Char(0)));` which they have in their code sample. – GSerg Nov 18 '19 at 09:10
  • @Fildor Oooh, got it. Thanks! I used ```char.IsControl()``` to remove non-printable characters. – butternutmilk_ Nov 18 '19 at 09:20
  • 2
    You are supposed to cut at the first `'0'`, not invent other ways. – GSerg Nov 18 '19 at 09:22
  • Is there a reason you are using BinaryReader and not for example [ReadAny](https://infosys.beckhoff.com/content/1033/tcsample_net/html/twincat.ads.sample07.htm?id=3126287095494571991) method? – Quirzo Nov 19 '19 at 06:29

0 Answers0