Possible to get last modified date of folder? - vb.net

I have a block of code which reads all the files in a directory, and gets the latest date from all those files. Not sure if I'm being silly, but is there a way to do the same thing but by getting the last modified date of the folders within that directory instead of the files?
Dim chkPath = "C:\CheckFolders"
Dim directory As New System.IO.DirectoryInfo(chkPath)
Dim File As System.IO.FileInfo() = directory.GetFiles()
Dim File1 As System.IO.FileInfo
Dim LastModified As String
For Each File1 In File
LastModified = System.IO.File.GetLastWriteTime(chkPath & "\" & File1.Name).ToShortDateString()
Next
MsgBox(LastModified)

Instead of hoping that the directory entries are returned in ascending date order, you should actively find the latest one. You can do that with the LINQ Max method like this:
Shared Function GetLatestFileModified(d As String) As DateTime
Dim di = New DirectoryInfo(d)
Dim latest = di.EnumerateFiles().Max(Function(i) i.LastWriteTimeUtc)
Return latest
End Function
Shared Function GetLatestDirectoryModified(d As String) As DateTime
Dim di = New DirectoryInfo(d)
Dim latest = di.EnumerateDirectories().Max(Function(i) i.LastWriteTimeUtc)
Return latest
End Function
For example,
Dim src = "C:\temp"
Console.WriteLine(GetLatestFileModified(src).ToShortDateString())
Console.WriteLine(GetLatestDirectoryModified(src).ToShortDateString())
might give
26/04/2019
10/04/2019

I have the following code in my solution.
'Check if file needs updating
Dim infoStkReader As System.IO.DirectoryInfo
infoStkReader = My.Computer.FileSystem.GetDirectoryInfo(SUI)
Dim CurrentdirectoryDate As DateTime = infoStkReader.LastWriteTime
Where SUI is the directory path.
Thanks,
Richard.

Related

Capture date from file name as a parameter then rename the file

Not sure if this is possible but each day a file will be sent to a folder: Z:\prod\DataProcessing\temp
The file name will look like this: 20230215_UniqueProductsFile.txt
I am wondering if it is possible to
a) search the folder for the version of the file with a date
b) capture the date to use as a parameter for another process
c) rename the file to UniqueProductsFile.txt overwriting the existing one in the folder from the previous days load
Any help would be appreciated.
a) search the folder for the version of the file with a date b) capture the date to use as a parameter for another process
This is possible using the IO.File.Exists method (documentation) to check if the file exists. For example:
Private Function UniqueProductsFileExistsByDate(directory As String, value As DateTime, ByRef output As String) As Boolean
Dim filename = $"{value:yyyyMMdd}_UniqueProductsFile.txt"
Dim path = IO.Path.Combine(directory, filename)
Dim fileExists = IO.File.Exists(path)
If (fileExists) Then
output = path
End If
Return fileExists
End Function
c) rename the file to UniqueProductsFile.txt
This is possible using IO.File.Move (documentation) where the first argument is the ByRef value set in the UniqueProductsFileExistsByDate method and the second argument is the new name:
Dim directory = IO.Path.Combine("Z:", "prod", "DataProcessing", "temp")
Dim value = DateTime.Today
Dim path As String
If (UniqueProductsFileExistsByDate(directory, value, path)) Then
Dim newPath = IO.Path.Combine(directory, "UniqueProductsFile.txt")
IO.File.Move(path, newPath)
End If

How to represent testfile name using regular expression in VB

Newbie here. I have the following code in VB for reading csv file. Filename includes current date so it changes daily. How do I represent the filename using regular expression so it will read any csv file? Thanks
Dim objReader = New IO.StreamReader("\\FolderA\FolderB\SEBCTS20220831.csv")
I have tried -
objReader = New IO.StreamReader("\\FolderA\FolderB\^SEBCTS\w\w\w\w\w\w\w\w\.csv$")
'objReader = New IO.StreamReader("\\FolderA\FolderB\^\w\w\w\w\w\w\w\w\w\w\w\w\w\w\.csv$")
But I get an error -
Error: Could not find a part of the path '\FolderA\FolderB^SEBCTS\w\w\w\w\w\w\w\w.csv$'.
Why you need regex, use Date.TryParseExact and Path.GetFileNameWithoutExtension:
Dim file = "\\FolderA\FolderB\SEBCTS20220831.csv"
Dim fileName = Path.GetFileNameWithoutExtension(file)
Dim format = "yyyyMMdd"
Dim possibleDate = If(fileName.Length >= format.Length, fileName.Substring(fileName.Length - format.Length), Nothing)
Dim parsedDate As Date
Dim isValidFile = Date.TryParseExact(possibleDate, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, parsedDate)
If you not even want to ensure that the last digits of the file-name is a valid date but also today:
isValidFile = isValidFile AndAlso parsedDate.Date = Date.Today

GetFiles is incredibly slow vb.NET

I need to process a large amount of files and scour thru a group of directories and subdirectories and get the file from the found directory. This is easy using a simple directory but when scouring a thousand directories, the program slows down to a crawl. I've heard of using enumeratefiles but I'm not how to approach this. thank you.
How should I approach this?
dim Filename_to_lookfor as string
dim filePaths As String()
for i = 0 to 1000
Filename_to_lookfor = array(i)
filePaths = Directory.GetFiles(sTargetPath, sFilename_to_lookfor.ToUpper,
IO.SearchOption.AllDirectories)
if filepath.length > 0 then
'copy file using Computer.FileSystem.CopyFile()
end if
next
Thank you.
Another coding would be using Linq:
Sub SearchFiles(pathAndfileNames_to_lookfor() As String, sTargetPath As String)
' Call just once Directory.GetFiles():
Dim FilePaths() As String = Directory.GetFiles(sTargetPath, "*.*", IO.SearchOption.AllDirectories)
Dim lookup1 = FilePaths.ToLookup(Function(x) x.ToLower)
Dim lookup2 = pathAndfileNames_to_lookfor.ToLookup(Function(x) x.ToLower)
Dim filesInBoth = lookup1.SelectMany(Function(x) x.Take(lookup2(x.Key).Count).ToArray)
For Each file In filesInBoth
'copy file using Computer.FileSystem.CopyFile()
Console.WriteLine(file)
Next
End Sub
Calling the procedure would be as follows:
Dim file1 As String = "C:\...\file1..."
Dim file2 As String = "C:\...\file2..."
Dim pathAndfileNames_to_lookfor() As String = New String() {file1, file2}
Dim sTargetPath = "..."
SearchFiles(pathAndfileNames_to_lookfor, sTargetPath)

Filter Files and Order By Modify Date VB

I'm filtering files by multiple extensions and i want to order by files date.
I'm trying
GetFiles().OrderByDescending(Function(p) p.LastWriteTime)
but cant order like this.
Dim driver As DriveInfo = DriveInfo.GetDrives().Where(Function(x) x.DriveType = DriveType.Removable).FirstOrDefault
If driver IsNot Nothing AndAlso driver.IsReady Then
UsbRootPath = Path.GetPathRoot(driver.RootDirectory.ToString)
Dim ext = {".png", ".jpg", "*.zip"}
Dim rootFiles() As String = ext.SelectMany(Function(f) Directory.GetFiles(driver.RootDirectory.ToString, f, SearchOption.TopDirectoryOnly)).ToArray()
End If
I'm trying GetFiles().OrderByDescending(Function(p) p.LastWriteTime)
Well, that doesn't work because you use it in a SelectMany, so in kind of a sub-query. You need to apply the ordering last. Also, p is a String, the path, you need File.GetLastWriteTime:
Dim rootFiles() As String = ext.
SelectMany(Function(f) Directory.EnumerateFiles(driver.RootDirectory.ToString, f, SearchOption.TopDirectoryOnly)).
OrderByDescending(Function(f) File.GetLastWriteTime(f)).
ToArray()
I would suggest that you use the DirectoryInfo and FileInfo classes:
Dim fileInfos = extensions.SelectMany(Function(ext) New DirectoryInfo(driver.RootDirectory.FullName).
GetFiles("*" & ext)).
OrderBy(Function(fi) fi.LastWriteTime)
Exactly what you do from there depends on exactly what you want. If you want the full path of each file in an array:
Dim filePaths = fileInfos.Select(Function(fi) fi.FullName).ToArray()

Renaming all files in a folder

I'm wondering if it's possible to rename all the files in a folder with a simple program, using vb.NET
I'm quite green and not sure if this is even possible.
Lets say there is a folder containing the files:
Text_Space_aliens.txt, fishing_and_hunting_racoons.txt and mapple.txt.
Using a few credentials:
Dim outPut as String = "TextFile_"
Dim fileType as String = ".txt"
Dim numberOfFiles = My.Computer.FileSystem.GetFiles(LocationFolder.Text)
Dim filesTotal As Integer = CStr(numberOfFiles.Count)
Will it be possible to rename these, regardless of previous name, example:
TextFile_1.txt, TextFile_2.txt & TextFile_3.txt
in one operation?
I think this should do the trick. Use Directory.GetFiles(..) to look for specific files. Enumerate results with a for..each and move (aka rename) files to new name. You will have to adjust sourcePath and searchPattern to work for you.
Private Sub renameFilesInFolder()
Dim sourcePath As String = "e:\temp\demo"
Dim searchPattern As String = "*.txt"
Dim i As Integer = 0
For Each fileName As String In Directory.GetFiles(sourcePath, searchPattern, SearchOption.AllDirectories)
File.Move(Path.Combine(sourcePath, fileName), Path.Combine(sourcePath, "txtFile_" & i & ".txt"))
i += 1
Next
End Sub
In your title you state something about chronologically, but within your question you never mentioned it again. So I did another example ordering files by creationTime.
Private Sub renameFilesInFolderChronologically()
Dim sourcePath As String = "e:\temp\demo"
Dim searchPattern As String = "*.txt"
Dim curDir As New DirectoryInfo(sourcePath)
Dim i As Integer = 0
For Each fi As FileInfo In curDir.GetFiles(searchPattern).OrderBy(Function(num) num.CreationTime)
File.Move(fi.FullName, Path.Combine(fi.Directory.FullName, "txtFile_" & i & ".txt"))
i += 1
Next
End Sub
I've never done Lambdas in VB.net but tested my code and it worked as intended. If anything goes wrong please let me know.