From b4bd1aeaffb60a62099855113e06f63aed15aded Mon Sep 17 00:00:00 2001 From: Himmelt Date: Tue, 15 Aug 2023 18:04:22 +0800 Subject: [PATCH] Return expected length substring rather than throw an exception when reading strings --- S7.Net/Types/S7String.cs | 3 ++- S7.Net/Types/S7WString.cs | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/S7.Net/Types/S7String.cs b/S7.Net/Types/S7String.cs index d45c5349..2d1c3d8c 100644 --- a/S7.Net/Types/S7String.cs +++ b/S7.Net/Types/S7String.cs @@ -42,7 +42,8 @@ public static string FromByteArray(byte[] bytes) try { - return StringEncoding.GetString(bytes, 2, length); + int expect_length = bytes.Length - 2; + return StringEncoding.GetString(bytes, 2, Math.Min(expect_length, length)); } catch (Exception e) { diff --git a/S7.Net/Types/S7WString.cs b/S7.Net/Types/S7WString.cs index 001c7ef3..b63f3b39 100644 --- a/S7.Net/Types/S7WString.cs +++ b/S7.Net/Types/S7WString.cs @@ -31,7 +31,8 @@ public static string FromByteArray(byte[] bytes) try { - return Encoding.BigEndianUnicode.GetString(bytes, 4, length * 2); + int expect_length = (bytes.Length - 4) / 2; + return Encoding.BigEndianUnicode.GetString(bytes, 4, Math.Min(expect_length, length) * 2); } catch (Exception e) {