VB.NET directory.EnumerateFiles: Access to path X is denied - vb.net

Ok so I am trying to write a program to find a specific file on the C drive and get its location. However the following code does not work! I've researched this a lot and gone from GetFiles to Directory.enumerateFiles. However I keep running into an exception claiming that I have no access, simply ignoring the message (closing it/pressing ok) does not continue the search and instead stops it altogether, I need a way of bypassing this if possible, so If a directory causes an exception it will skip it and move along with no error on screen if possible.
Currently the manifest file is set to "requireAdministrator" so I know thats not the issue. Running VB as administrator does not solve, and running the compiled file as admin does not work either. Hope someone can help!
Note: I'm using Visual Basic 2010 Express and have no plans to upgrade to a newever version due to hardware limitation and operating system.
Imports System.IO
Public Class GuardianScanner
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.ReadOnly = True
TextBox1.ScrollBars = ScrollBars.Vertical
Button1.Enabled = False
TextBox1.AppendText(Environment.NewLine & "[INFO] Please wait while scanning. This can take a few minutes")
Try
For Each file As String In Directory.EnumerateFiles("C:\", "GodlyNorris.exe", SearchOption.AllDirectories)
TextBox1.AppendText(Environment.NewLine & "[INFO] Found virus: AUTONORRIS: " & file.ToString)
Next file
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

I tried posting this as a comment but it's pretty messy. This should work, basically it tries to create a directory out of every subdirectory in the C drive, and if it fails with the unauthorized access exception, it moves on to the next subdirectory.
For Each directory In New DirectoryInfo("C:\").GetDirectories()
Try
For Each file In directory.GetFiles("*", SearchOption.AllDirectories)
Try
TextBox1.Text += Environment.NewLine + file.Name
Catch ex As Exception
'MsgBox(ex.Message)
Continue For
End Try
Next
Catch ex As Exception
'MsgBox(ex.Message)
Continue For
End Try
Next

Related

Hangman System.IO.IOException' occurred in mscorlib.dll

i am creating a hangman game that is to be used on a few computers, i have created the hangman game itself but i am using the "load form" function to create the list when the program first starts, but i am having this issue.
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'h:\Bryson\words.txt' because it is being used by another process.
Using sw As StreamWriter = File.CreateText("h:\Bryson\words.txt")
^^that line is where the error pops up^^
I have inserted some in code Comments to make life easier. If anyone can help thanks in advance :)
'USED TO CREATE HANGMAN FILE IF NOT FOUND
Private Sub main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
fofound = False
fifound = False
MsgBox("remove this and change file path and fix qu2 quiz")
'DESIGNER USE
Dim path As String = "h:\Bryson\words.txt"
'CREATE VAR FOR PATH
If System.IO.Directory.Exists("h:\Bryson") Then
'CHECKS IF FOLDER EXISTS
fofound = True
Else
'IF IT DOES THEN IT MOVES ON
System.IO.Directory.CreateDirectory("h:\Bryson")
'IF NOT IT CREATES THE FOLDER
fofound = True
If File.Exists("h:\Bryson\test\words.txt") Then
'CHECKS IF FILE EXISTS
fifound = True
Else
'IF IT DOES IT MOVES ON
IO.File.Create("h:\Bryson\words.txt")
'IF NOT IT CREATES IT
FileClose()
End If
End If
If fofound And fifound = True Then
Else
Using sw As StreamWriter = File.CreateText("h:\Bryson\words.txt")
'CRASH POINT The process cannot access the file 'C:\Bryson\words.txt'
'because it Is being used by another process.
sw.WriteLine("Hangman")
sw.WriteLine("computer")
sw.WriteLine("electrode")
sw.WriteLine("independent")
sw.WriteLine("stream")
sw.WriteLine("enforcing")
End Using
'WRITES TO FILE
MsgBox("file created")
'DESIGNER USE
FileClose()
'CLOSES FILE
End If
End Sub
FileClose() is a legacy function from VB6 and will not affect anything in the System.IO namespace. To close a file you need to call .Close() or .Dispose() on the stream that has opened the file (wrapping the stream in a Using block does this automatically).
Your problem is this line:
IO.File.Create("h:\Bryson\words.txt")
The method creates a new file and opens a FileStream to it which locks the file. Since you never close the returned FileStream your file will remain locked until you close your application.
The File.Create() call is completely unnecessary though because File.CreateText() will create the file if it doesn't exist. So you should just remove the above line.

Startup Folder Permissions in VB.NET

I am building an app which installs all the company's bespoke software at the click of a button. Included in the list is an asset tracker/reporting tool which must run at startup for everyone. Our standard build (I have no control over this whatsoever) is Windows 10, and we also have some legacy Windows 7 machines around, but in each case the startup registry keys are locked down so I started to create shortcuts in C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup.
If the startup folder doesn't exist, then it creates the folder. Logged on as local admin, I can create the startup folder manually without UAC popping up, take ownership of the folder and assign Everyone to have modify access, creating a shortcut in there. When I log off/on, the software runs. However when I code this, I get permissions errors.
Here's the code:
Sub DetectFolders()
Dim sFolder1 As String = "C:\My Apps\"
Dim sFolder2 As String = "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\"
Dim sFolder3 As String = "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\"
If Not Directory.Exists(sFolder1) Then
Directory.CreateDirectory(sFolder1)
End If
If Not Directory.Exists(sFolder2) Then
Try
' create folder
TakeOwnership(sFolder3)
Application.DoEvents()
AddDirectorySecurity(sFolder3, "MyDomain\" & Environment.UserName, FileSystemRights.FullControl, AccessControlType.Allow)
Application.DoEvents()
Directory.CreateDirectory(sFolder2)
Application.DoEvents()
TakeOwnership(sFolder2)
' everyone has modify access // TEST
AddDirectorySecurity(sFolder2, "Everyone", FileSystemRights.Modify, AccessControlType.Allow)
Catch ex As Exception
MessageBox.Show(ex.Message, "Config", MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End Try
End If
End Sub
Sub TakeOwnership(ByVal sfolder As String)
' take ownership
Try
Dim ds As System.Security.AccessControl.DirectorySecurity
Dim account As System.Security.Principal.NTAccount
ds = System.IO.Directory.GetAccessControl(sfolder, System.Security.AccessControl.AccessControlSections.Owner)
account = New System.Security.Principal.NTAccount(System.Security.Principal.WindowsIdentity.GetCurrent.Name)
ds.SetOwner(account)
System.IO.Directory.SetAccessControl(sfolder, ds)
Application.DoEvents()
Catch ex As Exception
MessageBox.Show("" & ex.Message & "", "Take Ownership", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Sub AddDirectorySecurity(ByVal FileName As String, ByVal Account As String, ByVal Rights As FileSystemRights, ByVal ControlType As AccessControlType)
Try
' Create a new DirectoryInfoobject.
Dim dInfo As New DirectoryInfo(FileName)
' Get a DirectorySecurity object that represents the
' current security settings.
Dim dSecurity As DirectorySecurity = dInfo.GetAccessControl()
' Add the FileSystemAccessRule to the security settings.
dSecurity.AddAccessRule(New FileSystemAccessRule(Account, Rights, ControlType))
' Set the new access settings.
dInfo.SetAccessControl(dSecurity)
Catch ex As Exception
MessageBox.Show("" & ex.Message & "", "Add Security", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
The first two Errors that appear is: Attempted to perform an unauthorized Operation, generated from the first time that AddDirectorySecurity and TakeOwnership are called.
I then get an error which states:
Access to the path 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup' is denied.
This is generated from the directory.createdirectory line in DetectFolders sub
I'm rapidly beginning to run out of ideas to get this working. Is it something in my code? Am I missing something, or does windows 10 not work in this way. Any constructive help will be gratefully received.

Process Start and Errors from Slow Applications

I made an application that our company uses to launch databases and updates them on the users machine, when needed.
I am having a slight problem when it comes to launching databases and the database starts up slow. When this occurs my application throws an exception, as I assuming its awaiting some kind of response back.
As of now the error thrown is: The system cannot find the file specified
I am trying to prevent this exception logging for cases like this(Slow Application), but still allow the logging if a real error occurs while opening a database.
Current Code I am using:
Private Sub OpenApplication()
If File.Exists(LocalPathString) Then ' File Found. Open the File.
Try
Dim ps As New Process
ps = Process.Start(LocalPathString)
Catch ex As Exception
ex.Source += " | " & LocalPathString
RaiseEvent ShowError(ex)
Finally
RaiseEvent CancelIt() ' Thread Complete. Close the ActionForm
End Try
Else
If LocalPathString = vbNullString Then
RaiseEvent CancelIt() ' No file exits. Cancel thread.
Else
RaiseEvent ShowError(New Exception("Database Not Located: " & LocalPathString))
End If
End If
End Sub
StackTrace:
System.Diagnostics.Process.StartWithShellExecuteEx(startInfo As ProcessStartInfo)
App.exe: N 00912
System.Diagnostics.Process.Start()
App.exe: N 00136
System.Diagnostics.Process.Start(startInfo As ProcessStartInfo)
App.exe: N 00049
SAMi.ActionClass.OpenApplication()
App.exe: N 00117
Maybe I'm missing something, but why don't you simply omit the logging if you found that specific exception?
Catch ex As Exception
ex.Source += " | " & LocalPathString
if not ex.Message.Contains("The system cannot find the file specified") Then
RaiseEvent ShowError(ex)
end if

Can't delete file. File in use by another process

I have a program (simple file updater) which downloads a file. Before that, an old version of this file is queued for deletion. But if I edit this file e.g. in text editor (save and close it), then my program refuses to delete it.
I have sub like this
Private Sub delete_file(ByVal dir As String)
Try
If My.Computer.FileSystem.FileExists(dir) Then My.Computer.FileSystem.DeleteFile(dir)
Catch ex As Exception
Debug.WriteLine(ex.ToString())
Sleep(1000)
delete_file(dir)
End Try
End Sub
It never goes out of the recursion. Exception says that file is being used by other process, and waiting doesn't change anything.
Any clues?
[EDIT]
Changed Sub a bit, so it doesn't contain recursion in Exception handler
Private Sub delete_file(ByVal dir As String)
Dim ok As Boolean = True
Try
If My.Computer.FileSystem.FileExists(dir) Then My.Computer.FileSystem.DeleteFile(dir)
Catch ex As Exception
Debug.WriteLine(ex.ToString())
ok = False
End Try
If ok = False Then
Sleep(1000)
delete_file(dir)
End If
End Sub
Words "another process" are VERY ambiguous.
It turned out that other function from my program was opening the same file twice, and closing it only once. Fixing that removed problem with deleting it.
So when u're having the same error, try searching your program for other places when this file may be modified.
Thanks for comments, they surely gave me some hints about good programming.

How do I move or replace a file or folder in Visual Basic 2010?

When debugging I get the following error.
Unhandled exception has occurred
Could not complete operation since a file already exists in this path "C:\32bit\abc.dll"
How can I fix this issue?
Imports System
Imports System.IO
Public Class Form1
Private Sub ReactorButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReactorButton1.Click
If ReactorComboBox1.SelectedItem = "Some Program" Then
My.Computer.Network.DownloadFile _
("http://somesite/test/abc.dll", _
"C:\32bit\abc.dll", True, 500)
System.IO.File.Move("C:\32bit\abc.dll" "C:\Program Files\Some Program\abc.dll")
My.Computer.Network.DownloadFile _
("http://www.somerandomsite/test1/abcd _
"C:\64bit\abcd.dll", True, 500)
System.IO.File.Move("C:\64bit\abcd.dll… "C:\Program File (x86)\Some Other Program\abcd.dll")
End If
End Sub
I also have tried
Try
Catch ex As Exception
System.IO.File.Delete("C:\32bit\abc.dll")
End Try
Try
Catch ex As Exception
My.Computer.Network.DownloadFile _
("http://somesite.com/folder/32bit/abc.dll", _
"C:\32bit\abc.dll", True, 500)
End Try
System.IO.File.Copy("C:\32bit\abc.dll", "C:\Program Files (x86)\A Program\Sub Folder\abc.dll")
But I still get the same unhandled exception error.
It is because the file exists. You need to delete it before download (your version delete is in the wrong place, should be in Try, not Catch)
Check My.Computer.Network.DownloadFile Method. You can have a overwrite flag in DownloadFile:
overwrite is set to False and the destination file already exists (IOException).
Review My.Computer.Network.DownloadFile Method (MSDN).
FYI, it is bad coding practice to run code in the catch block. catch blocks are usually meant to truly catch the execption.
The issue you might be running into is that you are trying to move the file before it is completely downloaded and therefore you are getting the exception.