1

I'm opening a file using the OpenFile Dialog and I want to confirm that the file is in an excel format.

The file that I opened is "C:\Desktop\Distribution.xls", but both criteria of my if statement are evaluating to true. Is there another method that I should be using?

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

            }
Nicole
  • 104
  • 1
  • 2
  • 11
  • Doesnt explain the issue but you should use `System.IO.Path.GetExtension(openFileDialog1.FileName)!=".xls"` – Tim Schmelter May 02 '18 at 15:54
  • "myExcelFile.xls" -> `!File.EndsWith(".xlsx")` is true, `!File.EndsWith(".xls")` is false, `true || false` is true. – Blake Thingstad May 02 '18 at 15:56
  • In addition to what everyone has said, you might find the [`FileDialog.Filter`](https://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.filter(v=vs.110).aspx) property useful. – 41686d6564 stands w. Palestine May 02 '18 at 15:56
  • Using `||` operator: `true || true == true`, `true || false == true`, `false || true == true`, `false || false == false`. Using `&&` operator: `true && true == true`, `true && false == false`, `false && true == false`, `false && false == false`. So you're getting the `MessageBox.Show` method because `false || true == true`. – Ivan García Topete May 02 '18 at 15:58

5 Answers5

5

You need to be used "&&" instead of "||"

The If statement Can't ever be false because you're trying to evaluate that it ends with two different strings at the same time (which is impossible).

You want to say, "If file does not end in .xlsx and it also doesn't end with .xls, it is invalid"

Replace this:

if (!file.EndsWith(".xlsx")||!file.EndsWith(".xls"))

With:

if (!file.EndsWith(".xlsx") && !file.EndsWith(".xls"))

Alternative Solutions:

Use a better-reading structure, without a negative "IF", such as:

if (file.EndsWith(".xlsx") || file.EndsWith(".xls"))
{
    //Do stuff
}
else
{
     //Invalid
}

Or, as suggested in the comments:

string ext = Path.GetExtension(openFileDialog1.FileName);
if(ext.Equals(".xls") || ext.Equals(".xlsx"))
{
    // Do stuff
}
else
{
    // Invalid
}
Clay07g
  • 1,105
  • 7
  • 23
2

The condition !file.EndsWith(".xlsx") || !file.EndsWith(".xls") can not ever return true. Because the file name can not ends both with .xlsx and .xls.

The correct condition is with "and" operator: !file.EndsWith(".xlsx") && !file.EndsWith(".xls").

TcKs
  • 25,849
  • 11
  • 66
  • 104
1

Try to avoid negatives in if statements. If you switch the blocks around, you can do a test to see if the filename is valid like this

    if (file.EndsWith(".xlsx")||file.EndsWith(".xls"))
    {
        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();

    }
    else
    {
        MessageBox.Show("Incorrect file format.  Please save file in an .xls format");
    }

It's much more readable and easier to understand.

Hans Kilian
  • 18,948
  • 1
  • 26
  • 35
1

Just another improvement which is too long for a comment. If you want to check extensions use System.IO.Path.GetExtension. You can store the valid extensions in a collection. Also consider that an extension could be .XLS which is valid but not with your code.

string[] validExt = {".xls",".xlsx"};
string extension = System.IO.Path.GetExtension(openFileDialog1.FileName);
bool fileValid = validExt.Contains(extension, StringComparer.InvariantCultureIgnoreCase);
if(!fileValid)
{
   // ...
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

In addition to what everyone has said, you might find the FileDialog.Filter property useful.

You can use it to restrict the allowed extensions like this:

openFileDialog1.Filter = "Excel workbooks(*.xls;*.xlsx)|*.xls;*.xlsx";

That will only show files with ".xls" and ".xlsx" extensions, leaving the user with no choice but to select files with the right extensions.

Also, if you decided to validate the file extension, you should use case-insensitive comparison because it's very common to find paths with uppercase extensions (e.g., "SomeName.XLSX"). You can do that using the String.Equals method:

string ext = System.IO.Path.GetExtension(file);
if (!string.Equals(ext, ".xls", StringComparison.OrdinalIgnoreCase) &&
    !string.Equals(ext, ".xlsx", StringComparison.OrdinalIgnoreCase))
{
    //...
}

Note that even if you used FileDialog.Filter, you might still need to confirm that the selected file has the right extension in the FileDialog.FileOk event because OpenFileDialog could allow selecting shortcuts that refer to files with different extensions even though the allowed extensions are restricted by the Filter property.