I noticed that the UTF encoding used to encode strings in sharp7 is not the one used by TIA portal and the Siemens HMIs that use the Windows-1252 encoding instead.
Unfortunately that encoding is available in .NET framework up to 4.8, but is not part of the framework in recent releases, at least from 6.0.
I'm using a modified version of the two functions to write and read strings, but to be compatible with the newer frameworks you need to install the System.Text.Encoding.CodePages NuGet package (and that breaks the one-file philosophy).
I'm leaving here my functions in case anyone needs them:
#region Get/Set String (S7 String)
// Thanks to Pablo Agirre
public static string GetStringAt(byte[] Buffer, int Pos)
{
#if NET
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
#endif
int size = (int)Buffer[Pos + 1];
Encoding win1252 = Encoding.GetEncoding("Windows-1252");
return win1252.GetString(Buffer, Pos + 2, size);
}
public static void SetStringAt(byte[] Buffer, int Pos, int MaxLen, string Value)
{
#if NET
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
#endif
//int size = Value.Length;
Encoding win1252 = Encoding.GetEncoding("Windows-1252");
int size = Math.Min(win1252.GetByteCount(Value), MaxLen);
Buffer[Pos] = (byte)MaxLen;
Buffer[Pos + 1] = (byte)size;
Array.Copy(win1252.GetBytes(Value), 0, Buffer, Pos + 2, size);
}
#endregion
Also notice that UTF-8 can have multi-byte characters, so if you want to write and read the strings with that encoding (without visualizing them on siemens products), you must retrieve the size of the array from the GetByteCount function of the encoding: if you use the length of the string you lose a number of bytes at the end of the string equal to the sum of the bytes added in the encoding.
I noticed that the UTF encoding used to encode strings in sharp7 is not the one used by TIA portal and the Siemens HMIs that use the Windows-1252 encoding instead.
Unfortunately that encoding is available in .NET framework up to 4.8, but is not part of the framework in recent releases, at least from 6.0.
I'm using a modified version of the two functions to write and read strings, but to be compatible with the newer frameworks you need to install the System.Text.Encoding.CodePages NuGet package (and that breaks the one-file philosophy).
I'm leaving here my functions in case anyone needs them:
Also notice that UTF-8 can have multi-byte characters, so if you want to write and read the strings with that encoding (without visualizing them on siemens products), you must retrieve the size of the array from the GetByteCount function of the encoding: if you use the length of the string you lose a number of bytes at the end of the string equal to the sum of the bytes added in the encoding.