From d808ea5eb6944c782f452f5f3ed38a1ec9db22cc Mon Sep 17 00:00:00 2001 From: diego Date: Thu, 16 Jun 2022 17:21:23 +0200 Subject: [PATCH] Give the option of changing the Encoding used to serialize and deserialize S7String, instead of always using Encoding.ASCII --- S7.Net/Types/S7String.cs | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/S7.Net/Types/S7String.cs b/S7.Net/Types/S7String.cs index 5bc383e..671c8e6 100644 --- a/S7.Net/Types/S7String.cs +++ b/S7.Net/Types/S7String.cs @@ -9,6 +9,11 @@ namespace S7.Net.Types /// public static class S7String { + /// + /// The Encoding used when serializing and deserializing S7String (Encoding.ASCII by default) + /// + public static Encoding StringEncoding { get; set; } + /// /// Converts S7 bytes to a string /// @@ -30,7 +35,8 @@ namespace S7.Net.Types try { - return Encoding.ASCII.GetString(bytes, 2, length); + if (StringEncoding == null) StringEncoding = Encoding.ASCII; + return StringEncoding.GetString(bytes, 2, length); } catch (Exception e) { @@ -38,7 +44,6 @@ namespace S7.Net.Types $"Failed to parse {VarType.S7String} from data. Following fields were read: size: '{size}', actual length: '{length}', total number of bytes (including header): '{bytes.Length}'.", e); } - } /// @@ -54,9 +59,10 @@ namespace S7.Net.Types throw new ArgumentNullException(nameof(value)); } - if (reservedLength > 254) throw new ArgumentException($"The maximum string length supported is 254."); - - var bytes = Encoding.ASCII.GetBytes(value); + if (reservedLength > 254) throw new ArgumentException($"The maximum string length supported is 254."); + + if (StringEncoding == null) StringEncoding = Encoding.ASCII; + var bytes = StringEncoding.GetBytes(value); if (bytes.Length > reservedLength) throw new ArgumentException($"The provided string length ({bytes.Length} is larger than the specified reserved length ({reservedLength})."); var buffer = new byte[2 + reservedLength]; @@ -65,5 +71,13 @@ namespace S7.Net.Types buffer[1] = (byte)bytes.Length; return buffer; } + + /// + /// Initializes default static properties + /// + static S7String() + { + StringEncoding = Encoding.ASCII; + } } }