将以空值结尾的字符串与非以空结尾的字符串进行比较

本文关键字:结尾 字符串 比较 空值 | 更新日期: 2023-09-27 18:31:45

我使用System.Drawing.Imaging从图像目录中提取图像标签。我可以很好地拉动标签,但问题是 PropertyItem 上的字符串以空结尾,但我与之比较的字符串不是。我的问题是,如何在 C# 中将以空结尾的字符串与非以空结尾的字符串进行比较?

这是我正在运行的代码

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();
}

"str"的输出如下所示:

'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

将以空值结尾的字符串与非以空结尾的字符串进行比较

手动修剪空值可以完成以下答案所示的技巧:

从 System.Text.Encoding.Unicode.GetString 获取以 null 结尾的字符串