Visual Basic don't see application.evtx - vb.net

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

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")

Related

Edit Settings.txt Document within Program Files directory during AutoCAD runtime

I am trying to store the AutoCAD users' settings in a directory under their Program Files. Originally, I had everything stored in the users favorites folder, but I wanted to keep all the plugin documents/files within the same directory. So, I have been trying all kinds of options to get admin rights during runtime, but still have not been successful. This is, more or less, what I just recently tested:
Public Shared Sub GetAdminAccess()
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal)
Dim curIdentity As WindowsIdentity = WindowsIdentity.GetCurrent()
Dim principalPerm As PrincipalPermission = New PrincipalPermission(Nothing, "BUILTIN\Administrators")
principalPerm.Demand()
End Sub
<PrincipalPermissionAttribute(SecurityAction.Demand, Role:="BUILTIN\Administrators")>
Private Shared Sub CreateSettingsFile()
Try
IO.File.Create(SettingsFilePath)
SettingsFileData = DefaultFileData
Property_WindowsOnTop = True
Property_SaveBackups = False
Property_SkipCreateSite = False
Property_AlignmentZoomExtents = ToFullExtents
Property_SaveBackups_Method = _TxtValue_Generic_None
Property_SaveBackups_MainDirectoryPath = _TxtValue_Generic_None
Call SetUserSettings(SettingsFileData)
Call SetPropertySettings()
Catch IOE As IO.IOException
MsgBox(IOE.Message)
Catch Ex As Exception
MsgBox(Ex.Message)
End Try
End Sub
Many of my attempts have resulted with this same error:
"Application attempted to perform an operation now allowed by the security policy. To grant this application the required permission, contact your system administrator, or use the Microsoft.NET Framework Configuration tool.
If you click Continue, the application will ignore this error and attempt to continue.
Request for principal permission failed."
An app can't write to the Program Files folder without administrator rights. The program files folder (and subfolders under it) are admin protected to prevent programs from replacing installed executable code with a malicious equivalent. Just don't do that.
If want app-specific data, use the appData folder. You can access that folder using System.Environment.SpecialFolder.ApplicationData and Environment.GetFolderPath
Get comfortable with the SpecialFolder enumeration (and with System.IO.Path.Combine). They are the correct way to access all of the well-known folders in the Windows OS.

Access to path is denied when trying to import from the client's desktop with SSIS

I'm creating a html page that will import an excel file in to a tracking system. On a button click event excel file is located / ssis package is fired / data imported then closed out. Thats the idea work flow. Problem is the excel file access is being denied before the package even executes
Here is the exact error :
I've tried :
excel file properties have been shared to everyone
identity impersonate set to true
hard coding the path
here is the VB code
Protected Sub bntExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
Dim app As Application = New Application()
Dim package As Package = Nothing
'Dim fileName As String = "C:\Users\Desktop\T. Bryant III\PTSID_Update_Template"'
Try
Dim fileName As String = Server.MapPath(System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName.ToString()))
FileUpload1.PostedFile.SaveAs(fileName)
package = app.LoadPackage("#C:\Users\Desktop\T.Bryant III\KitImport", Nothing)
'excel connection from package'
package.Connections("SourceConnectionExcel").ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0data source =" + fileName + "Extended Properties = Excel 8.0"
'Execute the pakage'
Dim results As Microsoft.SqlServer.Dts.Runtime.DTSExecResult = package.Execute()
Catch ex As Exception
Throw ex
Finally
package.Dispose()
package = Nothing
End Try
End Sub
Thanks in advance or if there is an easier way to do this please let me know. The package when executing it in ssis works fine with its own connection manager etc.
A few things to try. If they don't work for you as permanent solutions, they should at least confirm that your code is working and you are dealing with a persmissions issue (which appears to be the case).
Move your file to the public folder (C:\Users\Public).
Run your application (or web browser) as an administrator (if applicable to your version of Windows).
If you are using a web browser, try using a different one.
If nothing else works, try pasting your code into a Windows Form Application.
If you still get the same error after trying all of this, it's time to take another look at your code. Remove the Try/Catch block to determine precisely which line is throwing the error. If you've tried hard coding, I'm guessing it's the SaveAs method. I'm not sure what class FileUpload1 is, but some SaveAs methods won't overwrite existing files unless you explicitly tell them to. Check the appropriate documentation and see if you don't need to pass a True value somewhere along with filename.
Update us with the results. At the very least, this should narrow down your problem and allow for a better diagnosis of it.

VB.Net File.Exists() Returns True but Excel cannot Open

I check for the existence of the file with File.Exists(filePath). Then I try to open the file from within Excel with Excel.Workbooks.OpenText(filePath). But Excel complains that the file's not there. What the heck?
The context is that I am shelling out to another application to process a given file and produce a .out file, which I then convert to an Excel workbook.
'' At this point, filePath is a .txt file.
Dim args As String = String.Format("""{0}""", filePath)
...
Dim exe As String = Config.ExtractEXE
Dim i As New ProcessStartInfo(exe)
i.Arguments = args
Dim p As Process = Process.Start(i)
p.WaitForExit()
...
'' filePath now becomes the .out file.
'' Then eventually, I get around to checking:
'If Not File.Exists(filePath) Then
' MsgBox("Please ensure...")
' Exit Sub
'End If
'' In response to an answer, I no longer check for the existence of the file, but
'' instead try to open the file.
Private Function fileIsReady(filePath As String) As Boolean
Try
Using fs As FileStream = File.OpenRead(filePath)
Return True
End Using
Catch
Return False
End Try
End Function
Do Until fileIsReady(filePath)
'' Wait.
Loop
ExcelFile.Convert(filePath...)
'' Wherein I make the call to:
Excel.Workbooks.OpenText(filePath...)
'' Which fails because filePath can't be found.
Is there a latency issue, such that .Net recognizes the existence of the file before it's accessible to other applications? I just don't understand why File.Exists() can tell me the file is there and then Excel can't find it.
As far as I know, the only application that might have the file open is the application I call to do the processing. But that application should be finished with the file by the time p.WaitForExit() finishes, right?
I've had to deploy the application with this as a known bug, which really sucks. There's an easy workaround for the user; but still--this bug should not be. Hope you can help.
Whether or not a file exists is not the only factor in whether you can open it. You also need to look at file system permissions and locking.
File.Exists can lie to you (it returns false if you pass a directory path or if any error occurs, even if the file does exist)
The file system is volatile, and things can change even in the brief period between an if (File.Exists(...)) line and trying to open the file in the next line.
In summary: you should hardly ever use file.exists(). Almost any time you are tempted to do so, just try to open the file and make sure you have a good exception handler instead.

Access to Path Denied - Vb.Net

I have this small file search engine here made in VB.NET:
ListBox1.Items.Clear()
ListBox3.Items.Clear()
ChDir("C:\")
Try
For Each foundFile As String In My.Computer.FileSystem.GetFiles( _
My.Computer.FileSystem.CurrentDirectory, _
FileIO.SearchOption.SearchAllSubDirectories, TextBox4.Text & "*.*")
ListBox1.Items.Add(foundFile)
ListBox3.Items.Add(foundFile)
Next
Catch ex As UnauthorizedAccessException
MsgBox("Could not access file or not enough priveledges")
End Try
It searches through your whole C:\ for the file you entered. Although the problem I get is that some directories get access denied or not existing directories. How can I fix this problem?
Thanks
Some directories simply cannot be accessed like this. Use a try/catch loop with an empty catch to swallow errors and get the files that you can.
Try
'code for testing goes here
Catch
End Try
The above code when implemented properly should work if no error is thrown, and if no error is thrown then nothing will happen.
By granting privileges to the denied directories, and closing the programs that are locking the files within the directories.
MSDN says that, within the context of the GetFiles Method, an UnauthorizedAccessException means that the user lacks necessary permissions. See http://msdn.microsoft.com/en-us/library/t71ykwhb(VS.80).aspx
I would imagine that some directories are reserved by the file system, and you are not allowed certain types of access regardless of your privileges.

How do I create a folder in VB if it doesn't exist?

I wrote myself a little downloading application so that I could easily grab a set of files from my server and put them all onto a new pc with a clean install of Windows, without actually going on the net. Unfortunately I'm having problems creating the folder I want to put them in and am unsure how to go about it.
I want my program to download the apps to program files\any name here\
So basically I need a function that checks if a folder exists, and if it doesn't it creates it.
If Not System.IO.Directory.Exists(YourPath) Then
System.IO.Directory.CreateDirectory(YourPath)
End If
Under System.IO, there is a class called Directory.
Do the following:
If Not Directory.Exists(path) Then
Directory.CreateDirectory(path)
End If
It will ensure that the directory is there.
Try the System.IO.DirectoryInfo class.
The sample from MSDN:
Imports System
Imports System.IO
Public Class Test
Public Shared Sub Main()
' Specify the directories you want to manipulate.
Dim di As DirectoryInfo = New DirectoryInfo("c:\MyDir")
Try
' Determine whether the directory exists.
If di.Exists Then
' Indicate that it already exists.
Console.WriteLine("That path exists already.")
Return
End If
' Try to create the directory.
di.Create()
Console.WriteLine("The directory was created successfully.")
' Delete the directory.
di.Delete()
Console.WriteLine("The directory was deleted successfully.")
Catch e As Exception
Console.WriteLine("The process failed: {0}", e.ToString())
End Try
End Sub
End Class
Since the question didn't specify .NET, this should work in VBScript or VB6.
Dim objFSO, strFolder
strFolder = "C:\Temp"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FolderExists(strFolder) Then
objFSO.CreateFolder strFolder
End If
Try this: Directory.Exists(TheFolderName) and Directory.CreateDirectory(TheFolderName)
(You may need: Imports System.IO)
VB.NET? System.IO.Directory.Exists(string path)
Directory.CreateDirectory() should do it.
http://msdn.microsoft.com/en-us/library/system.io.directory.createdirectory(VS.71).aspx
Also, in Vista, you probably cannot write into C: directly unless you run it as an admin, so you might just want to bypass that and create the dir you want in a sub-dir of C: (which i'd say is a good practice to be followed anyways. -- its unbelievable how many people just dump crap onto C:
Hope that helps.
(imports System.IO)
if Not Directory.Exists(Path) then
Directory.CreateDirectory(Path)
end if
If Not Directory.Exists(somePath) then
Directory.CreateDirectory(somePath)
End If
You should try using the File System Object or FSO. There are many methods belonging to this object that check if folders exist as well as creating new folders.
I see how this would work, what would be the process to create a dialog box that allows the user name the folder and place it where you want to.
Cheers
Just do this:
Dim sPath As String = "Folder path here"
If (My.Computer.FileSystem.DirectoryExists(sPath) = False) Then
My.Computer.FileSystem.CreateDirectory(sPath + "/<Folder name>")
Else
'Something else happens, because the folder exists
End If
I declared the folder path as a String (sPath) so that way if you do use it multiple times it can be changed easily but also it can be changed through the program itself.
Hope it helps!
-nfell2009