VB.NET file filter - vb.net

I want get the oldest creation file in a directory but want to exclude the file ‘Startup’(Which is currently the oldest file). So I would like to skip that file and get the next oldest creation file in the directory which would be ‘TEST’.
This code only gets the Startup.
Dim oldestFile = folderlist.OrderBy(Function(fi) fi.CreationTime).First
1:

You use the Where function to filter.
Dim folder As New DirectoryInfo(folderPath)
Dim oldestFile = folder.EnumerateFiles().
Where(Function(fi) fi.Name <> "Startup.txt").
OrderBy(Function(fi) fi.CreationTime).
First()
Note that it is preferable to use EnumerateFiles rather than GetFiles unless you really want access to the full array of files after the fact. If you only need that one file, EnumerateFiles is better because it doesn't get all the files first and then perform the other operations on that array. You may already know this but most people don't at first.
Note also that I'm assuming that those are text files based on the icons. Change the name in the filter if they are something else. As a developer, you really ought to switch off the File Explorer feature that hides file extensions. That's for people who don't understand computers.

Related

How to check for any files with FileExists(String) method

I'm trying to automate a document handling process, and I need to check if there are any files inside a certain folder. The process itself removes the files from the folder once it finishes, so I need it to loop back and check if there are any files left.
So far I've been using a sample file like this:
File.Exists("C:\Users\gcaor\Desktop\OC\150.pdf")
150.pdf is the sample file it's searching for, but is there a way to search for any file at all? So that it returns true if there is a file in the folder and false if there isn't
You can use Directory.EnumerateFiles + Any:
Dim anyFileExist = Directory.EnumerateFiles(path).Any()
This is using standard .NET methods and also stops at the first file found.

VB.NET open a Text File within the same folder as my Forms without writing Full Path

I found a similar question but it was 5 years 8 months old, had 2 replies and neither worked for me (VB.Net Read txt file from current directory)
My issue is that when I use the following code:
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(Application.StartupPath & "\Username_And_Password_Raw.txt")
Dim usernameAndPassword = Split(fileReader, ",")
I get an error saying:
System.IO.FileNotFoundException: 'Could not find file 'C:\Users\wubsy\source\repos\NEA Stock Page System\NEA Stock Page System\bin\Debug\net6.0-windows\Username_And_Password_Raw.txt'.'
I have tried using all the different Applications.BLANKPath options I can find (ie; StartupPath, CommonAppDataPath, etc.) and they all return essentially the same error only with a different location.
This is the folder layout of my TXT File - I know it's a terrible, incredibly insecure and generally awful way of storing login information but this is just for a NEA so will never ever actually be used
This is the actual path of the TXT File if it helps
C:\Users\wubsy\source\repos\NEA Stock Page System\NEA Stock Page System\Username_And_Password_Raw.txt
The startup path is where your exe is located. That and all supporting files get copied to a binary directory when you compile in visual studio, in your case
C:\Users\wubsy\source\repos\NEA Stock Page System\NEA Stock Page System\bin\Debug\net6.0-windows
But what you're trying to do, reference the file where it sits in your solution, is probably not the best way to do it, and your code above will work (with a change, will mention later) if you change the properties of the file in the solution.
Right click on the file in the Solution Explorer Username_And_Password_Raw.txt, select Properties. Modify Copy to Output Directory to either Copy always / Copy if newer, depending on your requirement. Now that file will copy to the same directory your exe is in, and the code above should work.
Note, when creating a path, don't use string concatenation because you may have too many or too few \; use Path.Combine:
Dim filePath = Path.Combine(Application.StartupPath, "Username_And_Password_Raw.txt"
Dim fileContents = My.Computer.FileSystem.ReadAllText(filePath)

Either correct VB6/DOS/SQL function or suggest better alternative

I am currently reprogramming code made long ago by a less than skilled programmer. Granted the code works, and has for a number of years but it is not very efficient.
The code in question is in VB6 with SQL calls and it checks a particular directory on the drive (in this example we will use c:\files) and if a file exists, it moves the file to the processing directory loads the parameters for that particular file and processes them accordingly.
Currently the code uses the DIR function in VB6 to identify a file in the appropriate directory. The only problem is that if a number of files exist in the directory it is a crap shoot as to if it will grab the 5kb file and process it in 3 seconds or if it will grab the 500,000kb file and not process any others for the next 10 minutes.
I search many message boards to find some way to have it pick the smallest file and found I could build a complicated array to perform something similar to a sort but I decided to try alternate ideas instead to hopefully reduce processing time involved. Using ancient DOS knowledge I created something that should work, but for some reason is not (hence posting here).
I made a batch file that we will call c:\test.bat which contained the following lines:
delete c:\test.txt
dir /OS /B c:\files\*.txt>c:\test.txt
This deletes a prior existence of test.txt the pipes a directory without headers sorted by file size smallest to largest into c:\test.txt.
I then inserted the following code into the pre-existing code at the beginning:
Shell "c:\test.bat", vbHide
filepath = "c:\test.txt"
Open filepath For Input As #1
Input #1, filegrabber
Close #1
When I step through the code I can see that this works correctly, except now later on in the code I get a
Runtime error 91 Object variable or with block variable not set
in regard to assigning a FileSystemObject. Am I correct in guessing that FSO and Shell do not work well together? Also if you can suggest a better alternative to getting the smallest file from a existing directory suggestions are appreciated.
No need for sorting.
Just use Dir() to cruise through the directory. Before the loop set a Smallest Long variable to &H7FFFFFFF then inside the loop test each returned file name using the FileLen() function.
If FileLen() returns a value less than Smallest assign that size to Smallest and assign that file name to SmallestFile a String variable.
Upon loop exit if Smallest = &H7FFFFFFF there were no files, otherwise SmallestFile has your file name.
Seems incredibly simple, what am I missing?
Another approach is to use the FileSystemObject's Files collection. Just iterate the files collection for a given folder and evaluate each File object's Size property. So long as you don't have a million files in a folder or something, performance should be fine.

Retrieve the name of the most recent file in a directory using VB.Net

Let's say I am looking for a file that has a name that starts with GLNO1_
I can have hundreds of files that start with those characters, but I want to retrieve the name of the file that starts with those characters that is the most recently modified.
For example, Lets say I have files GLNo1_1, GLNo1_2, GLNo1_3 etc. up to _1000
and number 556 is the file that was modified the most recent.
In VB.Net, how do I retrieve that file name.
The file extensions are of .csv
You'll have to enumerate the files and pick the last one. That's a job for Linq:
Dim dir = New System.IO.DirectoryInfo("c:\foo\bar")
Dim file = dir.EnumerateFiles("GLNo1_*.csv").
OrderByDescending(Function(f) f.LastWriteTime).
FirstOrDefault()
If file IsNot Nothing Then
Dim path = file.FullName
'' etc..
End If
Never overlook the odds that there will be more than one "last one". If your program hasn't run for a while then more than one file could easily have been added by whatever software generates the *.csv files. You generally need to keep track of the files you've already seen before.

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()