Original TruncateBytes extension method wasn't working right, seemed to include an extra character which would put us over the limit. Replaced it and new method seems to be working as expected albeit not as nice looking.

This commit is contained in:
barelyprofessional
2025-02-09 16:23:35 +08:00
parent f0fc79c142
commit 42e6589e2a
2 changed files with 14 additions and 7 deletions
+13 -5
View File
@@ -115,10 +115,18 @@ public static class Extensions
public static string TruncateBytes(this string s, int limitBytes)
{
return Encoding.UTF8.GetString(
Encoding.UTF8.GetBytes(s)
.Take(limitBytes)
.ToArray()
).TrimEnd();
if (string.IsNullOrEmpty(s) || limitBytes <= 0)
{
return string.Empty;
}
if (s.Utf8LengthBytes() <= limitBytes)
{
return s;
}
var bytes = Encoding.UTF8.GetBytes(s);
var charCount = Encoding.UTF8.GetCharCount(bytes, 0, limitBytes);
return s.Substring(0, charCount);
}
}