首页 > 解决方案 > 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();

            }

标签: c#ends-with

解决方案


您需要使用“&&”而不是“||”

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
}

推荐阅读