Avoid files in use when automatically deleting files in VB.net - vb.net

I'm trying to make something that cleans files, basically deletes everything inside the folder. I face an issue how ever, when trying to clean %temp%, I run in to the issue that some files are in use inside %temp% file. How can I avoid these? Or just make it so it creates an exception for files that are in use. Here is my code :
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim directoryName As String = "C:\Windows\Temp"
For Each deleteFile In Directory.GetFiles(directoryName, "*.*", SearchOption.TopDirectoryOnly)
File.Delete(deleteFile)
Next
MsgBox("Temp Files Cleaned", MsgBoxStyle.Information)
End Sub
I also need it to permanently delete files, not just send to recycle bin.

Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim directoryName As String = "C:\Windows\Temp"
For Each deleteFile In Directory.GetFiles(directoryName, "*.*", SearchOption.TopDirectoryOnly)
Try
File.Delete(deleteFile)
Catch ex As IOException
Continue For
End Try
Next
MsgBox("Temp Files Cleaned", MsgBoxStyle.Information)
End Sub
The above code will swallow the "In use" error and go on with the deletion process.

As honeyboy says some like the following:
Try
File.Delete(deleteFile)
Catch fe As System.IO.IOException
'do something
Finally
End Try

Related

Async Download file updating the gui

I am downloading a file using webclient handling DownloadProgressChanged and DownloadFileCompleted.
My code is working whenever I am not updating the gui with percentage,b but In case I am going to update just a single label with it, then it kind of freezing in random situations. Doesn't matter if the file is little or big.
Public WithEvents mclient As New WebClient
Private Sub Download()
Dim filepath As String = (filepath..)
mclient.Encoding = Encoding.UTF8
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
mclient.Headers.Add(HttpRequestHeader.UserAgent, "")
mclient.DownloadFileAsync(New Uri(link), filepath)
End Sub
Private Sub mClient_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles mclient.DownloadProgressChanged
Try
'file website missing Content-Length, so getting the real size parsing html (real size=label7)
label1.text= ((e.BytesReceived) / 1048576).ToString("0.00") & "/" & Label7.Text
Catch ex As Exception
End Try
End Sub
Private Sub mClient_DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs) Handles mclient.DownloadFileCompleted
Try
label2.text="Download ended"
Catch ex As Exception
End Try
End Sub
How can I keep label1.text updated without using it inside of DownloadProgressChanged?
If I use a variable on it, where can I keep it updated? I don't want to use a timer though..

How get the DataDirectory path for MS Access MDB file

I have code which asks the user for a folder path and then copies an MDB file to that folder for back-up. However, the MDB is being copied from the wrong folder. How can I fix it so that it uses the right data folder when backing-up and restoring the MDB?
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Try
Dim fbd As New FolderBrowserDialog
If fbd.ShowDialog() = vbOK Then
System.IO.File.Copy("MHC.mdb", fbd.SelectedPath & "\MHC.mdb")
MsgBox("Done")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnRestore_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRestore.Click
Try
Dim fbd As New FolderBrowserDialog
If fbd.ShowDialog() = vbOK Then
File.Delete("MHC.mdb")
System.IO.File.Copy(fbd.SelectedPath & "\MHC.mdb", "MHC.mdb")
MsgBox("Done")
Application.Restart()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Yes I want to know the DataDirectory path.
The |DataDirectory| path placeholder as used in a connection string similar to this example:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Northwind.MDB
may be retrieved using code similar to this:
Dim objDataDir As Object = AppDomain.CurrentDomain.GetData("DataDirectory")
Dim dataDirectory As String = TryCast(objDataDir, String)
Beware that the above code can return Nothing (null) for dataDirectory. The only scenario that I know of that sets a "DataDirectory" is an application published using ClickOnce.
If dataDirectory is null, then you probably want to assign the Application.StartupPath property to it.
I do not know of any official documentation that states this is the proper procedure, but the code is based off of the ExpandDataDirectory method.
There is also a non-publicly scoped DataDirectory Property on the AppDomain.CurrentDomain.ActivationContext object, but you would need to use reflection to retrieve that property.
Note that if you want to use the |DataDirectory| placeholder, but point it to a path of your choice, you can use:
AppDomain.CurrentDomain.SetData("DataDirectory", "your path here")

How to catch exception when attempting to delete a file in use?

I't making a program to delete the files in my temp folder. I've gotten as far as the code to delete the files, But I can't seem to figure out how to skip the files in use or catch the exception so that my program doesn't crash when it attempts to delete a file in use.
Here is the code I have so far:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
If CheckBox1.Checked = True Then
Dim s As String
For Each s In System.IO.Directory.GetFiles("C:\Users\" + System.Environment.UserName + "\AppData\Local\Temp")
System.IO.File.Delete(s)
Next s
End If
end sub
Use a Try/Catch block to catch errors (exceptions)
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
If CheckBox1.Checked = True Then
Dim s As String
For Each s In System.IO.Directory.GetFiles("C:\Users\" + System.Environment.UserName + "\AppData\Local\Temp")
Try
System.IO.File.Delete(s)
Catch ex As Exception
Console.WriteLine("File could not be deleted : {0}", ex.Message)
End Try
Next s
End If
end sub
That will allow your program to ignore the error and continue processing the next items.
When an exception is thrown, once it is handled by the Catch, execution will jump to the End Try. Therefore, where you place the beginning and ending of your Try/Catch block is important. For instance:
Try
Dim s As String
For Each s In System.IO.Directory.GetFiles("C:\Users\" + System.Environment.UserName + "\AppData\Local\Temp")
System.IO.File.Delete(s)
Next s
Catch ex As IOException
End Try
In the above example, if any call to Delete fails, it will jump to the End Try and skip the rest of the iterations of the For loop (thereby skipping the rest of the files). However, consider this:
Dim s As String
For Each s In System.IO.Directory.GetFiles("C:\Users\" + System.Environment.UserName + "\AppData\Local\Temp")
Try
System.IO.File.Delete(s)
Catch ex As IOException
End Try
Next s
In this second example, it will jump to the End Try and then continue to the next iteration of the For loop (thereby continuing on the the next file in the list).
Also, as noted in the comments, above, you definitely ought to be using Path.GetTempPath to get the path to the temporary folder. You should not construct the path yourself, since it could change. For instance, Windows does not require that you user folder has to be under C:\Users. You can actually change that.

Searching a drive with vb.net

I am making a program that searches your drive for an executable.
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim di As New DirectoryInfo("C:\")
Dim files() As FileInfo
Dim a As Integer
Do While a = 0
Try
files = di.GetFiles("FileName.exe", SearchOption.AllDirectories)
Catch ex As UnauthorizedAccessException
End Try
If Not files Is Nothing Then
a = 1
End If
Loop
txt_Location.Text = files(0).FullName
End Sub
As soon as it hits the first UnauthorizedAccessException, it gets stuck in an infinite loop. How do I skip over the files that produce the exception?
EDIT:
This is what I have now:
Public Sub DirSearch(ByVal sDir As String)
Dim dir As String
Try
For Each dir In Directory.GetDirectories(sDir)
For Each file In Directory.GetFiles(dir, "Filename.exe")
ComboBox1.Items.Add(file)
Next
DirSearch(dir)
Next
Catch ex As Exception
Debug.WriteLine(ex.Message)
End Try
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
DirSearch("C:\")
End Sub
You need recursion here which handles each folder.
EDIT: As requested by the OP, a little example:
Public Sub DirSearch(ByVal sDir As String)
Try
For Each dir as String In Directory.GetDirectories(sDir)
For Each file In Directory.GetFiles(dir, "yourfilename.exe")
lstFilesFound.Items.Add(file)
Next
DirSearch(dir)
Next
Catch ex As Exception
Debug.WriteLine(ex.Message)
End Try
End Sub
Also take a look at the following answers:
Looping through all directory's on the hard drive (VB.NET)
How to handle UnauthorizedAccessException when attempting to add files from location without permissions (C#)
Also note, if you have enough access rights, you could simplify your code to this:
Dim di as New DirectoryInfo()
Dim files = di.GetFiles("iexplore.exe", SearchOption.AllDirectories) 'already returns all files at once
And at last but not least:
Avoid having infinite loops. Like in your example, they can lead to broken code just because some circumstances aren't like you've expected them to be. Imagine your code has run on your PC and you deployed this software to a customer - horrible scenario. ;-)

How to correctly enumerate files in selected path?

Visual Studio 2008 (vb.net)
I made simple anivirus but when I make Full scan by this code:
FolderBrowserDialog1.SelectedPath = ("C:\")
'first scan:************************************
Try
For Each strDir As String In
System.IO.Directory.GetDirectories(FolderBrowserDialog1.SelectedPath)
For Each strFile As String In System.IO.Directory.GetFiles(strDir)
ListBox1.Items.Add(strFile)
Next
Next
'Start the timer:
Catch ex As Exception
End Try
Timer1.Start()`
Just scan the first 6 files ...
I think the problem from Windows Folder permissions (Windows - Program Files ...etc)
So how to fix it?
Put a Console.WriteLine(ex) in your catch block so you can see any exceptions that are thrown. You'll probably see your problem then. Most likely permissions.
You could try the following:
For Each strFile As String In System.IO.Directory.GetFiles(strDir, "*", IO.SearchOption.AllDirectories)
Edit:
You could try the last solution found in this thread:
http://www.vbforums.com/showthread.php?t=624969
I tried this myself and it was super slow, but worked fine.
Public Class Form1
Private Sub foo(ByVal aDir As String)
Try
Dim di As New IO.DirectoryInfo(aDir)
Dim aryFiles() As IO.FileInfo = di.GetFiles("*.*")
Dim aryDirs() As IO.DirectoryInfo = di.GetDirectories()
For Each fi As IO.FileInfo In aryFiles
rslts.Add(fi.FullName)
Next
For Each d As IO.DirectoryInfo In aryDirs
foo(d.FullName)
Next
Catch ex As Exception
'Stop 'the catch should be more specific
End Try
End Sub
Dim rslts As List(Of String)
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
rslts = New List(Of String)
foo("C:\")
ListBox1.Items.Clear()
ListBox1.Items.AddRange(rslts.ToArray)
End Sub
End Class
It looks like your solution essentially loops through the first folder it can find and stops there. This solution is a bit different as it will recursively go through all the files and folders based on the start location.