0

I pulling image tags from a directory of images using System.Drawing.Imaging. I can pull the tags just fine, but the problem is the string coming off the PropertyItem is null terminated but the string I'm comparing it to is not. My question is, how do I compare a null terminated string to a non-null terminated string in C#?

Here is the code I'm running

byte[] tagBytes = new byte[tag.Length * sizeof(char)];
System.Buffer.BlockCopy(tag.ToCharArray(), 0, tagBytes, 0, tagBytes.Length);

pnl_slider.Visible = false;
string relativePath = ConfigurationManager.AppSettings["PhotoPathRelative"];
DirectoryInfo info = new DirectoryInfo(ConfigurationManager.AppSettings["PhotoPathPhysical"]);
FileInfo[] Files = info.GetFiles("*.jpg").OrderBy(p => p.CreationTime).ToArray();
foreach (FileInfo file in Files)
{
    System.Drawing.Image img = new Bitmap(file.FullName);
    foreach (PropertyItem item in img.PropertyItems)
    {
        if (item.Id == 40094)
        {
            str += "'" + Encoding.Unicode.GetString(item.Value).Trim() + "' " + BitConverter.ToString(item.Value) + " == " + BitConverter.ToString(tagBytes) + "<br/>";
        }
    }
    img.Dispose();
}

The output of 'str' looks something like this:

'wildlife' 77-00-69-00-6C-00-64-00-6C-00-69-00-66-00-65-00-00-00 == 77-00-69-00-6C-00-64-00-6C-00-69-00-66-00-65-00
'wildlife' 77-00-69-00-6C-00-64-00-6C-00-69-00-66-00-65-00-00-00 == 77-00-69-00-6C-00-64-00-6C-00-69-00-66-00-65-00
'wildlife' 77-00-69-00-6C-00-64-00-6C-00-69-00-66-00-65-00-00-00 == 77-00-69-00-6C-00-64-00-6C-00-69-00-66-00-65-00
'macro' 6D-00-61-00-63-00-72-00-6F-00-00-00 == 77-00-69-00-6C-00-64-00-6C-00-69-00-66-00-65-00
Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77
  • just call `Encoding.Unicode.GetString(item.Value).Trim()` on the byte arrays, the output string should be the same, you see in the output the last `00-00` has been stripped by the decoder. – kennyzx Nov 25 '14 at 03:33
  • @kennyzx I gave it a try and no dice, same issue. `if(Encoding.Unicode.GetString(item.Value).Trim() == Encoding.Unicode.GetString(tagBytes).Trim())` – Chris Stillwell Nov 25 '14 at 03:42
  • 1
    Looks like you have to trim the terminator [manually](http://stackoverflow.com/a/864274/815938), I thought this was done by the decoder but I was wrong. – kennyzx Nov 25 '14 at 04:07

1 Answers1

0

Trimming the nulls manually did the trick as shown in this answer:

Getting null terminated string from System.Text.Encoding.Unicode.GetString

Community
  • 1
  • 1
Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77