0

I am having a hard time figuring up why this code of mine gives me an unhandled exception error where in fact it is an if statement..

        If (Not System.IO.File.Exists("C:\file.txt") And System.IO.File.ReadAllText("C:\file.txt").Length <> "20") Then
            MessageBox.Show("Code executed!")
        Else
            MessageBox.Show("Failed to execute!")
        End If

Can you please tell me what have I missed?

  • You are executing both the `File.Exists` and the `ReadAllText` in all cases (including when `File.Exists` returns `False`. You should use `AndAlso` instead of `And`. That will ensure that the second test is not performed if the first one is `False`. – Blackwood Jan 16 '16 at 01:01
  • I'm surprised .Length <> "20" compiles. Shouldn't it be .Length <> 20 ? – Scott Hutchinson Jan 16 '16 at 01:38
  • @ScottHutchinson I think because because .Length returns a string that's why you need to add quotations.... However if it returns an integer then you don't need to add quotations... – Phoenix Eve Aspacio Jan 16 '16 at 01:46
  • Of course, but I assume it returns an integer. The fact that it compiles must mean that you don't have Option Strict On, which I recommend you change. See this article: https://support.microsoft.com/en-us/kb/311329 – Scott Hutchinson Jan 16 '16 at 02:01
  • I would separate the two conditions into separate if statements. Also if you could post the message from the exception that could help us to debug. – Scott Hutchinson Jan 16 '16 at 02:41
  • It's hard to see how this could be a duplicate of a question that the OP didn't know was involved. – Blackwood Jan 16 '16 at 03:12
  • Just check this - https://gist.github.com/wingedpather/50f75d5faa5eb2a63e7d – Vivek S. Jan 16 '16 at 11:16
  • @wingedpanther thanks.. – Phoenix Eve Aspacio Jan 16 '16 at 11:18

1 Answers1

0

It is better to break down code as shown below which makes detecting and debugging a whole lot easier. Better to write a few extra lines so what happen here does not happen at all.

Dim fileName As String = "C:\file.txt"
Dim FileText As String = ""

If IO.File.Exists(fileName) Then
    FileText = IO.File.ReadAllText(fileName)
    If FileText.Length <> 20 Then
        MessageBox.Show("Code executed!")
    Else
        ' recover
    End If
Else
    MessageBox.Show("Failed to execute!")
End If
Karen Payne
  • 4,341
  • 2
  • 14
  • 31