AdsBinaryWriter.WritePlcAnsiString Method

Writes a string as a PLC string to the current stream.

Namespace:  TwinCAT.Ads
Assembly:  TwinCAT.Ads (in TwinCAT.Ads.dll) Version: 4.3.0.0

Syntax

C#

public void WritePlcAnsiString(
    string value,
    int length
)

VB

Public Sub WritePlcAnsiString ( 
    value As String,
    length As Integer
)

Parameters

value

Type: System.String
The string to write to the stream.

length

Type: System.Int32
The length of the string without '\0' terminator!

Remarks

This method is meant for writing single string variables defined in the PlcControl format. E.g. to write a 'STRING(80)' (byte size is 81) a length of '80' must be given to the 'length' parameter. If the string length is larger or equal than the length parameter, then only length characters are written to the AdsStream (without terminating character). If the string value character count is shorter than the specified length parameter, the string + a terminating \0 will be added to the AdsStream. This method cannot be used for marshalling purposes, for example several fields of a struct, because no filling bytes will be written to the stream. In that case use the WritePlcAnsiStringFixedLength(String, Int32) method.

Examples

The following code shows how to Read/Write ANSI string values..

Read/Write ANSI Strings

using (TcAdsClient client = new TcAdsClient())
{
    client.Connect(851); // Connect to local port 851 (PLC)

    int handle = client.CreateVariableHandle("MAIN.string"); // Symbol "string" in MAIN defined as string

    try
    {
    // Read ANSI String string[80]
    int byteSize = 81; // Size of 80 ANSI chars + /0 (STRING[80])
    AdsStream readStream = new AdsStream(byteSize); // Size of 80 ANSI chars + /0 (STRING[80])
    AdsBinaryReader reader = new AdsBinaryReader(readStream);
    client.Read(handle, readStream, 0, byteSize); // Read 81 bytes
    string value = reader.ReadPlcString(byteSize,Encoding.Default);

    // Write ANSI String string[80]
    AdsStream writeStream = new AdsStream(byteSize);
    AdsBinaryWriter writer = new AdsBinaryWriter(writeStream);
    value = "Changed";
    writer.WritePlcString(value, 80,Encoding.Default); // Max 80 characters!
    client.Write(handle, writeStream, 0, byteSize);
    }
    finally
    {
    client.DeleteVariableHandle(handle);
    }
}

Reference

AdsBinaryWriter Class

TwinCAT.Ads Namespace

AdsBinaryWriter.WritePlcAnsiStringFixedLength(String, Int32)

AdsBinaryWriter.WritePlcUnicodeString(String, Int32)

AdsBinaryWriter.WritePlcUnicodeStringFixedLength(String, Int32)