当然,您可以将文件内容读入列表,然后检查输入字符串是否包含在列表中(使用不区分大小写的比较)。如果是,您只需将字符串替换为列表中的字符串:
// The input string we want to format
var input = "IFCPERSONANDORGANIZATION";
// Read the file containing your class names into an array
var filePath = @"f:\public\temp\classnames.txt";
var knownClassNames = File.ReadAllLines(filePath);
// See if the list contains the name using a case-insensitive comarison.
// If it does, `FirstOrDefault` will return a non-null value, so we assign the result
// Otherwise, if it returns null (which is checked by `??`) we leave it as is.
input = knownClassNames
.FirstOrDefault(name => name.Equals(input, StringComparison.OrdinalIgnoreCase))
?? input;
这可以放入一个简单的函数中,您可以从任何地方调用它:
public static string CorrectClassNameCasing(string input)
{
var filePath = @"f:\public\temp\classnames.txt";
var knownClassNames = File.ReadAllLines(filePath);
return knownClassNames
.FirstOrDefault(name => name.Equals(input, StringComparison.OrdinalIgnoreCase)) ?? input;
}
对于我的示例,我创建了一个文件,其中仅包含您在示例中提到的一个类名:
static void Main()
{
Console.WriteLine(CorrectClassNameCasing("IFCPERSONANDORGANIZATION"));
Console.WriteLine(CorrectClassNameCasing("THISDOESNOTEXIST"));
Console.Write("\nDone!\nPress any key to continue...");
Console.ReadKey();
}
结果如下: