C#String EndsWith返回真实问题

Nic*_*ole 0 c# ends-with

我正在使用OpenFile对话框打开一个文件,我想确认该文件是excel格式.

我打开的文件是"C:\ Desktop\Distribution.xls",但我的if语句的两个条件都评估为true.我应该使用另一种方法吗?

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

            }
Run Code Online (Sandbox Code Playgroud)

Cla*_*07g 5

您需要使用"&&"而不是"||"

如果语句不能永远是假的,因为你要评估它与在同一时间两个不同的字符串结束(这是不可能的).

想要说的,"如果文件不存在的.xlsx结束它也不会.xls结束,它是无效的"

替换这个:

if (!file.EndsWith(".xlsx")||!file.EndsWith(".xls"))
Run Code Online (Sandbox Code Playgroud)

附:

if (!file.EndsWith(".xlsx") && !file.EndsWith(".xls"))
Run Code Online (Sandbox Code Playgroud)

替代方案:

使用更好的阅读结构,没有负"IF",例如:

if (file.EndsWith(".xlsx") || file.EndsWith(".xls"))
{
    //Do stuff
}
else
{
     //Invalid
}
Run Code Online (Sandbox Code Playgroud)

或者,正如评论中所建议的那样:

string ext = Path.GetExtension(openFileDialog1.FileName);
if(ext.Equals(".xls") || ext.Equals(".xlsx"))
{
    // Do stuff
}
else
{
    // Invalid
}
Run Code Online (Sandbox Code Playgroud)