Deleting temp folder files with vb.net - vb.net

I’m trying to programmatically clear out my temps folder however it can't delete files that are in use, which would be okay as long as it would then delete all the files not in use. However my code basically demands either we delete all or none, not just those not in use.
Below is the code could anybody please tell me how I can work around this?
'Deletes files in temporary directory...
Dim MYDAYS_2 As String
Dim MYTEMPFOLDER As String = System.IO.Path.GetTempPath
'this reads the regestry key otherwise gives a default value in its place (365)...
MYDAYS_2 = Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\AA", "HELLO", "365")
'Deletes all files older then the day specifyed in the variable MDAYS...
For Each file As IO.FileInfo In New IO.DirectoryInfo(MYTEMPFOLDER).GetFiles("*.*")
If (Now - file.CreationTime).Days > MYDAYS_2 Then file.Delete()
Next

You could use a simple try/catch:
For Each file As IO.FileInfo In New IO.DirectoryInfo(MYTEMPFOLDER).GetFiles("*.*")
If (Now - file.CreationTime).Days > MYDAYS_2 Then
Try
file.Delete()
Catch
' log exception or ignore '
End Try
End If
Next

Related

Deleting Files in Subfolder and delete empty Folders

I have to write a PlugIn (in VB.NET) that deletes files after a set amount of days. I've been using this Code to "delete" all files older then DataAge:
For testing purposes I use Log(file.Name) instead of file.Delete().
Dim directory As New IO.DirectoryInfo(.PluginXML.DeleteDirectory) //.PluginXML.DeleteDirectory = FilePath
For Each file As IO.FileInfo In directory.GetFiles()
If (Now - file.CreationTime).Days > .PluginXML.DataAge Then Log(file.Name) //.PluginXML.DataAge = FileAge
Next
How do I check for old files/empty folders in Subfolders from .PluginXML.DeleteDirectory?
I tried something like this, but it would delete the folders, instead of old files.
For Each folder As IO.DirectoryInfo In directory.GetDirectories()
If (Now - folder.CreationTime).Days > .PluginXML.DataAge Then Log(folder.FullName)
Next
One option is to use the overload of GetFiles (or even better*, EnumerateFiles) that accepts a SearchOption with which you can specify that it recurses all directories. For example:
For Each file As FileInfo In directory.EnumerateFiles("*.*", SearchOption.AllDirectories)
If (Now - file.CreationTime).Days > .PluginXML.DataAge Then Log(file.Name)
Next
The alternative is to create a recursive function that walks the directory tree using EnumerateDirectories:
Public Sub ProcessDirectory(directory as DirectoryInfo, dataAge as Integer)
For Each file As FileInfo In directory.EnumerateFiles()
If (Now - file.CreationTime).Days > dataAge Then Log(file.Name)
Next
For Each subDir as DirectoryInfo In directory.EnumerateDirectories()
ProcessDirectory(subDir, dataAge)
Next
End Sub
And then call the method using your base/root path
Dim rootDir As New DirectoryInfo(.PluginXML.DeleteDirectory)
ProcessDirectory(rootDir, .PluginXML.DataAge)
Though note that you will probably need to add error handling for when a directory is inaccessible, such as when an UnauthorizedAccessException or SecurityException is thrown.
* GetFiles loads all files into memory at once whereas EnumerateFiles returns an IEnumerable<FileInfo> that streams the results. This has benefits if you are dealing with directories that contain lots of files, especially if using the AllDirectories option.

How to transfer a file from one directory to another that is the newest file

I am trying to transfer a file from one directory to another that is the current and latest file in that folder, however I cannot use Robocopy to do this, since it fails when the server is logged out. Is there another way I can do this in Vb.net?
Thank you.
you can use File.Copy(Source,Destination,Overwrite?) to overwrite the file with a newer one, or
If File.Exists(destination) Then File.Delete(destination);
' Move the file.
File.Move(source, destination);
to move the file... I pesonally prefer:
File.Copy(Source,Destination,true)
File.Delete(Source)
To move the file and overwrite it if it exists :)... less code
Here's the code to move the latest file to another directory
Dim SourceDirectory As String = "C:\sourcedirectory\"
Dim SaveDirectory As String = "C:\targetdirectory\"
Dim LatestFile as IO.FileInfo = Nothing
'Let's scan the directory and iterate through each file...
Dim DirInfo As New IO.DirectoryInfo(SourceDirectory)
For Each file As IO.FileInfo In DirInfo.GetFiles()
If LatestFile Is Nothing Then
'This is the first time we run any permutations, so let's assign this file as "the latest" until we find one that's newer
LatestFile = file
ElseIf file.CreationTime > LatestFile.CreationTime Then
'Changes the "Latest file" if this file was created after the previous one.
'You can also change the check to .LastAccessTime and .LastWriteTime depending on how you want to define "the newest"...
LatestFile = file
End If
Next
'Now we move the file, but first, check to see if we actually did find any file in the source directory
If NewestFile IsNot Nothing Then
NewestFile.CopyTo(SaveDirectory & NewestFile.Name,true) 'will copy and overwrite existing file
'Now we can delete the old one
NewestFile.Delete()
Else
'Could not find the newest file, or directory might be empty...
End If
'Done!
Hope that Helps

Move only newest file over from one server to the other

I am trying to move only one file that is the newest created or edited from a directory to another folder on two different servers. How would I only move the newest file from one directory to the next instead of all the files in the folder?
Here is the code I am using to move the file over.
My.Computer.FileSystem.CopyDirectory("\\172.16.1.42\s$\SQLBackup\FWP", "\\172.16.1.22\F$\BackupRestore", True)
It shouldn't be too hard to determine which file is the newest one. A simple way to do this would be to retrieve information about all the files in a directory and then cycle through them to find the most recent.
You could do something like this:
Imports System.IO
Dim di As New IO.DirectoryInfo("c:\") ' Change this to match your directory
Dim diar1 As IO.FileInfo() = di.GetFiles()
Dim dra As IO.FileInfo
Dim mostRecentFile As IO.FileInfo = Nothing
Dim mostRecentTimeStamp As DateTime = Nothing
DateTime.TryParse("01/01/1900 0:00:00", mostRecentTimeStamp) ' Set to early date
For Each dra In diar1 ' Cycle through each file in directory
If File.GetLastAccessTime(dra.FullName) > mostRecentTimeStamp Then
mostRecentTimeStamp = File.GetLastAccessTime(dra.FullName)
mostRecentFile = dra
End If
Next
Debug.Print(mostRecentFile.FullName) ' Will show you the result
' Use mostRecentFile.Copy to copy to new directory
Hopefully that solves your problem. If not, let me know. There may be an issue about this routine detecting hidden files, so if you see something like that, post back here. You will also want to add code to detect if no new file is found, for example.

Visual Basic FileSystem.GetFiles

I'm making a console application and I want to see what files is in a folder
For Each foundFile As String In My.Computer.FileSystem.GetFiles("c:\users\zac\desktop\booked vehicle\requested\")
Console.WriteLine(foundFile)
Next
after using this code and find that the folder is empty I need an If statement that say's
If foundfile has no files then
tell user no files found
end if
but I don't know how to write this so Visual Basic understands.
Load the files into a variable then check the count.
Dim files = My.Computer.FileSystem.GetFiles("c:\users\zac\desktop\booked vehicle\requested\")
If files.Count = 0 Then
'tell user no files
Else
For Each file In files
Console.WriteLine(file)
Next
End If
FileSystem.GetFiles() returns a collection of file name strings. As OneFineDay showed, you can use the collection's Count property to know if any files were found.
The downside of using FileSystem.GetFile() is that it has to search the entire folder before then returning the entire list of filenames. If you are searching large folders and speed is an issue, consider using Directory.EnumerateFiles() instead. That way, you can output a message if no file was found, otherwise loop throuh the list of found files. For example:
Dim files = Directory.EnumerateFiles("c:\users\zac\desktop\booked vehicle\requested\").GetEnumerator()
If files.MoveNext Then
' files were found
Do
Console.WriteLine(files.Current)
Loop Until Not files.MoveNext
Else
' no files were found
End If
I personally would use Linq to accomplish this. It's very quick and efficient to use in this case. I put the Console.ReadLine() at the end to show the files, you can remove this if need to be. Also you can change the Console.WriteLine to not include the string (s) if you don't want to. The s was declared if you want to show the files and also to see if there are any files. As I said, this was for my viewing to see the files. Straight to the point!
Dim s As String = String.Join(Environment.NewLine, New DirectoryInfo("YOUR DIRECTORY").GetFiles().[Select](Function(file) file.Name).ToArray)
Console.WriteLine(If(s.Length > 0, s, "No files found!"))
Console.ReadLine()

Moving and Deleting Files in a Loop in VB.Net

I'm trying to improve a system I have that already works. However I've ran into a problem I can't seem to find an answer to using google, perhaps I'm not searching the right questions?
I'm using a For Each loop to gather files in a directory. I then try to get each file name and some other information and determine if I should move the file temporarily or delete the file.
Example of the code used:
For Each File In Directory.GetFiles(Profile)
Dim tmpFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(File) 'Never moves to the next file.
Dim Name As String = tmpFile.Name
Dim AccessDate As String = tmpFile.LastWriteTime.Date()
Dim CurrentDate As String = My.Computer.Clock.LocalTime.Date()
If AccessDate < CurrentDate Then
My.Computer.FileSystem.DeleteFile(File) 'Moves to the next file without any issues.
Threading.Thread.Sleep(150) 'If no sleep program will lock up
Else
If Not Directory.Exists(Path) Then
Directory.CreateDirectory(Path)
My.Computer.FileSystem.MoveFile(File, Path & Name)
Else
My.Computer.FileSystem.MoveFile(File, Path & Name)
End If
End If
Next
I have defined in the code what my problem is, and forgive me if there is a better way to do this, I'm self taught and still learning many things. If there's an easier way please point me in that direction.
Essentially I hit an error saying "File not found" on the move because tmpFile is not moving to the next File in the directory.