C#按指定字节长度截取字符串(每个汉字长度2字节)-C/S开发框架

public static string DoTrimString(string str, int byteLength)
{
if (string.IsNullOrEmpty(str)) return "";
if (System.Text.Encoding.UTF8.GetByteCount(str) < byteLength) return str;
int i = 0;
int j = 0;
foreach (char newChar in str)
{
if ((int)newChar > 127)
{
i += 2;
}
else
{
i++;
}
if (i <= byteLength)
j++;
else
break;
}
str = str.Substring(0, j);
return str;
}