Question

I am getting data from Device(Time attendance) using C++ library in C# 4.0, issue is that with name field have some junk value.

Name field is byte array and I had try using Encoding.Default.GetString(user.Name), here user is a Struct.

[StructLayout(LayoutKind.Sequential, Size = 48, CharSet = CharSet.Ansi), Serializable]
public struct User
  {
  public int ID; 
  [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 12)]
  public byte[] Name; 
}

Output

"Jon\0 41 0"
"rakesh\0 6"

I want to remove \0 41 0 and \0 6.

Any help would be appreciated.

Était-ce utile?

La solution

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...

Autres conseils

RegEx is a best way for removing junk value, In this example with W I remove all character that is not word,

textBox1.Text = Regex.Replace("rakesh\0 6", "W", "");

You can find complete library for regex on http://regexlib.com/

do it like this

Regex re = New Regex("[\x0A\x0D]", RegexOptions.Compiled)

str = re.Replace(str.Trim(), String.Empty)

OR

 string str1="";
 for(int i = 0 ; i < str.lengh ; i++) { 
         if(!char.IsLetter(str[i])
              str1 += str[i];
 }

return str1

You are dealing with null-terminated strings. So you want to strip zero byte and all bytes after the zero byte in your arrays before passing it to Encoding.Default.GetString(byte[]).

Update:

Example code (may be not very optimal):

static byte[] RemoveJunk(byte[] input)
{
    var end = Array.IndexOf(input, (byte)0);
    Console.WriteLine(end);
    if (end < 0)
        return input;
    var result = new byte[end];
    Array.Copy(input, result, end);
    return result;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top