c# - C# String EndsWith 返回真问题
问题描述
我正在使用 OpenFile 对话框打开一个文件,并且我想确认该文件是 excel 格式。
我打开的文件是“C:\Desktop\Distribution.xls”,但我的 if 语句的两个条件都评估为真。我应该使用另一种方法吗?
DialogResult result = openFileDialog1.ShowDialog();
if (result==DialogResult.OK)
{
file = openFileDialog1.FileName;
file = file.Trim();
if (!file.EndsWith(".xlsx")||!file.EndsWith(".xls"))
{
MessageBox.Show("Incorrect file format. Please save file in an .xls format");
}
else
{
book = application.Workbooks.Open(file);
sheet = (Worksheet)book.Worksheets[1];
range = sheet.get_Range("A1", "A1".ToString());
range.EntireRow.Delete(XlDirection.xlUp);
sheet.Cells[1, 2].EntireColumn.NumberFormat = "@";
book.SaveAs(csvConverstion, XlFileFormat.xlCSV);
book.Close(false, Type.Missing, Type.Missing);
application.Quit();
}
解决方案
您需要使用“&&”而不是“||”
If 语句永远不能为假,因为您试图评估它同时以两个不同的字符串结尾(这是不可能的)。
您想说,“如果文件不以 .xlsx 结尾并且也不以 .xls 结尾,则它是无效的”
替换这个:
if (!file.EndsWith(".xlsx")||!file.EndsWith(".xls"))
和:
if (!file.EndsWith(".xlsx") && !file.EndsWith(".xls"))
替代解决方案:
使用更好的阅读结构,没有否定的“IF”,例如:
if (file.EndsWith(".xlsx") || file.EndsWith(".xls"))
{
//Do stuff
}
else
{
//Invalid
}
或者,正如评论中所建议的:
string ext = Path.GetExtension(openFileDialog1.FileName);
if(ext.Equals(".xls") || ext.Equals(".xlsx"))
{
// Do stuff
}
else
{
// Invalid
}
推荐阅读
- apache-kafka - 尝试使用 avro4s 定义序列化程序但缺少隐式错误
- android-room - Android Room Database Drop table UI 测试
- django - 如何通过 django 内联表单中的外键字段进行查询?
- reporting-services - 计算 SSRS 中的中位数
- sql - 检查 SQL Server 上的常用密码
- c# - 在 c# 中通过 npgsql 打开与 Denodo 的连接时出现错误消息
- python - Python & PyQt5:如何获取帧的 RGB 颜色值?
- react-native - 优化 FlatList 项性能的最佳方法
- extjs - Extjs如何参数化商店代理url
- reporting-services - SSRS 报告参数 当当前日期为星期一时,开始日期设置为星期五