2

I have a problem with "Application.evtx" file. Everytime I run my script I get the message box with "File not found" information and I don't know why. I ran Visual Studio as administrator. Help me with this one, please.

Imports System.IO

Module Module1
    Sub Main()
        Dim pathReadFile As String = "c:\Windows\System32\winevt\Logs\Application.evtx"
        'Dim pathReadFile As String = "%windir%\Sysnative\winevt\Logs\Application.evtx"
        'Dim pathReadFile As String = "D:\Dokumenty\MyTest.txt"

        Try
            If File.Exists(pathReadFile) Then
                MsgBox("File found.")
            Else
                MsgBox("File not found.")
            End If
        Catch ex As Exception

        End Try
    End Sub
End Module
ManoDestra
  • 6,325
  • 6
  • 26
  • 50
Brath
  • 53
  • 1
  • 5

1 Answers1

1

Don't use File.Exists(). Ever.

There are many reasons for this, but the one that impacts you right now is that it lies to you and tells you the file does not exist, even if the file actually does exist and the real problem is that you don't have permissions to use it. From the docs:

Return Value
Type: System.Boolean
true if the caller has the required permissions and path contains the name of an existing file; otherwise, false

Remember that normal users have extremely limited file system permissions outside of their own home folders, and even Administrator users need to explicitly run a process as elevated or UAC will just give them normal user permissions.

You have to handle the exception anyway if reading the file fails. Put your development effort into the exception handler.

While I'm here, you may also want to build your path like this:

Dim pathReadFile As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "winevt\Logs\Application.evtx")
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • 2
    If he's running a 32-bit application on a 64-bit system he might also experience the problem that `System32` is redirected to `SysWOW64`. For this one shall use `Sysnative` instead. – Visual Vincent Jul 18 '16 at 20:16
  • Can I force the system to give my script permission to file? How can I replace File.Exists()? – Brath Jul 19 '16 at 05:27
  • @Brath You have to run as a user that has file permissions, and you have to get elevation. For File.Exists()... you really don't need it. _Just try to open the file_, whether or not it exists, and handle the exception when you fail. As bad as exceptions are, file I/O is so much worse. – Joel Coehoorn Jul 19 '16 at 13:57