Keep it simple:
static class StringExtensions
{
public static string TrimNullTerminatedString(this string s)
{
if (s == null)
throw new NotImplementedException();
int i = s.IndexOf('\0');
if (i >= 0)
return s.Substring(0, i);
return s;
}
}
Use it like this:
string name = Encoding.Default.GetString(user.Name).TrimNullTerminatedString();
That being said, a better option would be to handle that at declaration level. If Name
is a string, there is no reason to declare it as byte[]
; declare it as a string, and the null terminating character will be handled properly:
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 12)]
public string Name;
It would also be easier to manipulate in code...