与StartsWith或Substring的字符串比较不起作用

时间:2014-10-23 13:34:41

标签: c# .net

我需要找到我从电子邮件中下载的附件,但我无法将附件文件名与字符串进行比较,我做错了什么?脚本应该返回“in in”但它返回“out out”

FileAttachment fileAttachment = item.Attachments[0] as FileAttachment;

Console.WriteLine(fileAttachment.Name);

if (fileAttachment.FileName.StartsWith("OpenOrders")) {
    Console.WriteLine("in"); 
} 
else { 
    Console.WriteLine("out"); 
}

if (fileAttachment.FileName.Substring(0, 10) == "OpenOrders") { 
    Console.WriteLine("in"); 
} else { 
    Console.WriteLine("out"); 
}

输出:

OpenOrders some text with spaces.xlsx
out
out

2 个答案:

答案 0 :(得分:2)

您正在输出fileAttachment.Name,但在fileAttachment.FileName中使用StartsWith。使用正确的版本,它应该工作。

FileAttachment fileAttachment = item.Attachments[0] as FileAttachment;

Console.WriteLine(fileAttachment.Name);

if (fileAttachment.Name.StartsWith("OpenOrders")) {
    Console.WriteLine("in"); 
} 
else { 
    Console.WriteLine("out"); 
}

if (fileAttachment.Name.Substring(0, 10) == "OpenOrders") { 
    Console.WriteLine("in"); 
} else { 
    Console.WriteLine("out"); 
}

答案 1 :(得分:2)

您正在输出Name属性:

Console.WriteLine(fileAttachment.Name);

但您的StartsWithSubstring来电是针对FileName财产的。我怀疑您会发现Name正在返回与FileName不同的内容。