Capture date from file name as a parameter then rename the file - vb.net

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

Related

Possible to get last modified date of folder?

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.

Create a text file with date and time as the filename

I'm trying to create a text file with Visual Studio in VB.Net, and I want the filename to be the current date and time.
I have this code:
Dim d As System.DateTime
DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
Dim filepath As String = d + ".txt"
If Not System.IO.File.Exists(filepath) Then
System.IO.File.Create(filepath).Dispose()
End If
But every time I use d it gives me the System.NotSupportedException error. I can only create a text file by specifying the filename. How can i fix it and make my text file's name the current date and time?
Your code fails to assign a value to the variable called d. Also, you want d to be a string, not a DateTime. Finally, the / and : characters in from your date and time are not valid in a windows filename. Either remove them or replace them with valid characters. Replace your first three lines of code with:
Dim d As String = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss")
Dim filepath As String = d & ".txt"
You are trying with '/' and ':' in file name, while creating file this special characters not allowed.
Dim dateString = DateTime.Now.ToString("yyyyMMdd_HH_mm_ss")
Dim filepath As String = dateString + ".txt"
If Not System.IO.File.Exists(filepath) Then
System.IO.File.Create(filepath).Dispose()
End If

Directory.GetFiles(strFolderPath) EXCLUDING Certain File Names VB.NET

How would a do a Directory.GetFiles and exclude files called "abc" and "xyz"?
Basically I have a DIR where all the files exist and a particular group of files has to be sent to one department and the the "abc" and "xyz" file need to be sent to another?
At the moment I do this:
'Standard Documents
Dim strAttachments As List(Of String) = New List(Of String)
strAttachments.AddRange(Directory.GetFiles(GlobalVariables.strFolderPath))
I need the same functionality but excluding the files and then do a similar command as above to include the files to another address.
Cheers,,
James
UPDATE
Dim exclude = {"ATS_Declaration"}
Dim myFiles = From fn In Directory.EnumerateFiles(GlobalVariables.strFolderPath)
Where Not exclude.Contains(Path.GetFileNameWithoutExtension(fn), StringComparer.InvariantCultureIgnoreCase)
Dim strAttachments As List(Of String) = New List(Of String)(myFiles)
You can use LINQ and System.IO.Path.GetFileNameWithoutExtension:
Dim exclude = { "abc", "xyz" }
Dim myFiles = From fn in Directory.EnumerateFiles(GlobalVariables.strFolderPath)
Where Not exclude.Contains(Path.GetFileNameWithoutExtension(fn), StringComparer.InvariantCultureIgnorecase)
Dim strAttachments As List(Of String) = New List(Of String)(myFiles)
Note that i have used EnumerateFiles since that does not need to load all into memory first.
I couldn't get the answers here to exclude the file (not sure why Contains fails to match unless the file name is exactly the same as the exclusion string)
The answer below works wonderfully
Check this out: Exclude files from Directory.EnumerateFiles based on multiple criteria

Check if part of file name exists in a path using .net

I would like to check in my weapplication if a file exists in a path provided. File name can be anything eg:pic.jpg, pic.txt,pic1.txt,pic2.jpg etc.
I need to check if "pic" name exists in the path.Only check if 'pic' exists or pic+anything+.jpg or pic.anything.txt exists using vb.net.
Please help.
You'll want to check the File.Exists method. Don't forget, this only work for finding files on the server, not the client. Finding a file on the client side is a totaly different mather.
You can get the list of files in the given directory and then check the filenames to see if the fragment of text you're looking for is in any of them. Assuming you want to include the extension in the test and you don't care if it is upper or lower case:
Function FilenameFragmentExists(srcDir As String, fragment As String) As Boolean
Dim files() As String = IO.Directory.GetFiles(srcDir)
Dim found As Boolean = False
For i = 0 To files.Length - 1
If IO.Path.GetFileName(files(i)).IndexOf(fragment, StringComparison.OrdinalIgnoreCase) > -1 Then
found = True
Exit For
End If
Next
Return found
End Function
Or you can do it in one line with LINQ, and if you are using .NET framework >=4 then you can use .EnumerateFiles instead of .GetFiles, which has a chance of being faster:
Function FilenameFragmentExists(srcDir As String, fragment As String) As Boolean
Return IO.Directory.EnumerateFiles(srcDir).Any(Function(f) IO.Path.GetFileName(f).IndexOf(fragment, StringComparison.OrdinalIgnoreCase) >= 0)
End Function
You should use Directory.GetFiles(path, pattern) to check if it returns some files corresponding to your pattern. For example
Dim files = Directory.GetFiles("C:\temp", "*.jpg")
if files.Length > 0 Then
Console.WriteLine("Directory contains " + files.Length + " with the required pattern")
Else
Console.WriteLine("Directory doesn't contain any file with the required pattern")
End if
In the second parameter you could pass any kind of pattern following the usual wildcard rules used for directory listing

Extract filename from path [duplicate]

This question already has answers here:
How to extract file name from path?
(16 answers)
Closed 1 year ago.
I need to extract the filename from a path (a string):
e.g.,
"C:\folder\folder\folder\file.txt" = "file" (or even "file.txt" to get me started)
Essentially everything before and including the last \
I've heard of using wildcards in place of Regex (as it's an odd implementation in VBA?) but can't find anything solid.
Cheers in advance.
I believe this works, using VBA:
Dim strPath As String
strPath = "C:\folder\folder\folder\file.txt"
Dim strFile As String
strFile = Right(strPath, Len(strPath) - InStrRev(strPath, "\"))
InStrRev looks for the first instance of "\" from the end, and returns the position. Right makes a substring starting from the right of given length, so you calculate the needed length using Len - InStrRev
Thanks to kaveman for the help. Here is the full code I used to remove both the path and the extension (it is not full proof, does not take into consideration files that contain more than 2 decimals eg. *.tar.gz)
sFullPath = "C:\dir\dir\dir\file.txt"
sFullFilename = Right(sFullPath, Len(sFullPath) - InStrRev(sFullPath, "\"))
sFilename = Left(sFullFilename, (InStr(sFullFilename, ".") - 1))
sFilename = "file"
I was looking for a solution without code. This VBA works in the Excel Formula Bar:
To extract the file name:
=RIGHT(A1,LEN(A1)-FIND("~",SUBSTITUTE(A1,"\","~",LEN(A1)-LEN(SUBSTITUTE(A1,"\","")))))
To extract the file path:
=MID(A1,1,LEN(A1)-LEN(MID(A1,FIND(CHAR(1),SUBSTITUTE(A1,"\",CHAR(1),LEN(A1)-LEN(SUBSTITUTE(A1,"\",""))))+1,LEN(A1))))
`You can also try:
Sub filen()
Dim parts() As String
Dim Inputfolder As String, a As String
'Takes input as any file on disk
Inputfolder = Application.GetOpenFilename("Folder, *")
parts = Split(Inputfolder, "\")
a = parts(UBound(parts()))
MsgBox ("File is: " & a)
End Sub
This sub can display Folder name of any file
Here's simpler method: a one-line function to extract only the name — without the file extension — as you specified in your example:
Function getName(pf):getName=Split(Mid(pf,InStrRev(pf,"\")+1),".")(0):End Function
...so, using your example, this:
       MsgBox getName("C:\folder\folder\folder\file.txt")
  returns:
       
For cases where you want to extract the filename while retaining the file extension, or if you want to extract the only the path, here are two more single-line functions:
Extract Filename from x:\path\filename:
Function getFName(pf)As String:getFName=Mid(pf,InStrRev(pf,"\")+1):End Function
Extract Path from x:\path\filename:
Function getPath(pf)As String: getPath=Left(pf,InStrRev(pf,"\")): End Function
Examples:
(Source)
Using Java:
String myPath="C:\folder\folder\folder\file.txt";
System.out.println("filename " + myPath.lastIndexOf('\\'));
I used kaveman's suggestion successfully as well to get the Full File name but sometimes when i have lots of Dots in my Full File Name, I used the following to get rid of the .txt bit:
FileName = Left(FullFileName, (InStrRev(FullFileName, ".") - 1))
You can use a FileSystemObject for that.
First, include a reference for de Microsoft Scripting Runtime (VB Editor Menu Bar > Tools > References).
After that, you can use a function such as this one:
Function Get_FileName_fromPath(myPath as string) as string
Dim FSO as New Scripting.FileSystemObject
'Check if File Exists before getting the name
iF FSO.FileExists(myPath) then
Get_FileName_fromPath = FSO.GetFileName(myPath)
Else
Get_FileName_fromPath = "File not found!"
End if
End Function
File System Objects are very useful for file manipulation, especially when checking for their existence and moving them around. I like to use them early bound (Dim statement), but you can use them late bound if you prefer (CreateObject statement).
'[/vba]
' Keep It Simple
' .. why use FileSystemObject or Split when Left and Mid will do it
' the FSO has some 33 Subs or Functions
that have to be loaded each time it is created.
' and needs the file to exist ... yet is only a bit slower
... under twice time.. some good code in FSO
' conservation is good .. spare a few electrons. ????... save a few millionths of a sec
'Also
' .. why the format of a function that we all seem to use like
'
' .. Function GetAStr(x) as string
' dim extraStr as string
' a lot of work with extraStr..
' that could have been done with the string variable GetAStr
already created by the function
' then .. GetAStr=extraStr to put it in its right place
' .. End Function
Function GetNameL1$(FilePath$, Optional NLess& = 1)
' default Nless=1 => name only
' NLess =2 => xcopya.xls xcopyb.xls xcopy7.xlsm all as xcopy to get find latest version
' Nless = - 4 or less => name with name.ext worka.xlsm
GetNameL1 = Mid(FilePath, InStrRev(FilePath, "") + 1)
GetNameL1 = Left(GetNameL1, InStrRev(GetNameL1, ".") - NLess)
End Function
Function LastFold$(FilePath$)
LastFold = Left(FilePath, InStrRev(FilePath, "") - 1)
LastFold = Mid(LastFold, InStrRev(LastFold, "") + 1)
End Function
Function LastFoldSA$(FilePath$)
Dim SA$(): SA = Split(FilePath, "")
LastFoldSA = SA(UBound(SA) - 1)
End Function
[<vba]