Visual Basic FileSystem.GetFiles - vb.net

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

Related

VB.NET file filter

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.

How to extract a zip file to directory and overwrite?

I made a little program that downloads a .zip file from my website and then later it installs in a specific directory. It works fine unless a file with the same name already exists, then I get an error. This is the code I have.
If Form1.CheckBox1.Checked = True Then
Label4.Text = "Downloading Test File!"
wc.DownloadFileAsync(New Uri("http://www.example.com/TestFile.zip"), Directory + "\TestFile.zip")
While wc.IsBusy = True
Application.DoEvents()
End While
ListBox1.Items.Add("Test File")
End If
'Install
If Form1.CheckBox1.Checked = True Then
ZipFile.ExtractToDirectory(Directory + "\TestFile.zip", Directory_Select.TextBox1.Text)
ListBox2.Items.Add("Test File")
End If
So for example, if the files inside "TestFile.zip" have the same name as Install location, it will give me following error:
The file 'filePath` already exists.
It doesn't finish extracting because a file with the same name already exists. Deleting the file beforehand is not a good solution because there will be multiple files with the same name.
How can I replace while extracting?
Also is there a way to pause the program till the file finishes extracting since some files are large and it takes some time before they are extracted.
Thanks in advance for helping me out, I am new and still learning. Appreciate your help.
Although the ExtractToDirectory method doesn't support overwriting files by default, the ExtractToFile method has an overload which takes a second boolean variable that allows you to overwrite the file being extracted. What you can do is to iterate over the files inside the archive and extract them one by one using ExtractToFile(filePath, True).
I have created an extension method which does just that and have been using it for a while. Hope you find it useful!
Add the following module to your project:
Module ZipArchiveExtensions
<System.Runtime.CompilerServices.Extension>
Public Sub ExtractToDirectory(archive As ZipArchive,
destinationDirPath As String, overwrite As Boolean)
If Not overwrite Then
' Use the original method.
archive.ExtractToDirectory(destinationDirPath)
Exit Sub
End If
For Each entry As ZipArchiveEntry In archive.Entries
Dim fullPath As String = Path.Combine(destinationDirPath, entry.FullName)
' If it's a directory, it doesn't have a "Name".
If String.IsNullOrEmpty(entry.Name) Then
Directory.CreateDirectory(Path.GetDirectoryName(fullPath))
Else
entry.ExtractToFile(fullPath, True)
End If
Next entry
End Sub
End Module
Usage:
Using archive = ZipFile.OpenRead(archiveFilePath)
archive.ExtractToDirectory(destPath, True)
End Using
Side note: Don't concatenate strings to form a path out of its parts; use Path.Combine() instead.

How do you retrieve the file path from a checked list box that has multiple subfiles from different directories?

I've got a checked list box that populates files and subfiles from a selected location using a folder browser dialog. What I'm trying to accomplish is retrieve each location/directory of every checked item within that list. I'm using these locations as a spot to copy and paste new files into if that makes sense.
I should add that I'm new to coding, and I don't know how to do something as "complex" as this. This is also my first post and I apologize if this is an easier type question for you guys.
For Each file As IO.FileInfo In ListBox1.CheckedItems
Dim NewFileName As String = FindListBox2ItemThatContains(file.Name)
Dim lstfiles As String = Directory.GetFiles(FBD2.SelectedPath)
If NewFileName.Trim.Length > 0 Then
IO.File.Copy(file.FullName, IO.Path.Combine(FBD2.SelectedPath, "item parent folder", NewFileName.Trim), True)
End If
ProgressBar1.Increment(+1)
Next

How to get a filename without using for next

Using VB.Net
Get a file name without using for next from the directory
Dim filefound = Directory.GetFiles("C:\", "1.txt")
For Each inwardfile In filefound
Dim strFilename As String = Path.GetFileName(inwardfile)
Next
The above code is working fine, but i dont want to use for loop because i will always get one file at a time not the list of files also i am searching with filename not like "*.txt"
So How to modify the code, Any one can assist.
Your question is inconsistent which makes it very unclear. Do you want a file name or a collection of them? If you want filename not like "*.txt" then why use "1.txt" for GetFiles?
This will answer the title question How to get a filename without using for next. For this, assume a directory full of ".json" files. Some are named cs###.json (e.g. cs001.json) some are named vb###.json and many others.
Path would work to allow you to examine parts of the filename, but DirectoryInfo will provide access to some of that info via FileInfo objects. This uses EnumerateFiles to be able to filter out unwanted files so they are not even returned to your code/array variable.
Dim dix As New DirectoryInfo("C:\Temp\Json")
Get the json files which DO NOT start with CS. This will return an array of FileInfo objects in case you need to do further exclusions:
Dim jFile = dix.EnumerateFiles.Where(Function(f) f.Extension = ".json" AndAlso
f.Name.StartsWith("cs") = False).
ToArray()
Get the json files which ARE "*1.json" and DO NOT start with "cs". In this case, the last Select method will cause an array of filenames to be returned:
Dim jFile = dix.EnumerateFiles.Where(Function(f) f.Extension = ".json" AndAlso
f.Name.EndsWith("1.json") AndAlso
f.Name.StartsWith("cs") = False).
Select(Function(q) q.Name).
ToArray()
Change the Select to 'Function(q) q.FullName` if you want the full path name. These should come close to whatever you are really looking for.

VBA fails to find a file

I have a VBA script used to process Word documents. The first thing the program does is to create an index of the documents in a defined set of folders. It then goes through the list processing each of the indexed documents.
The problem I am having is that it will sometimes decide that a particular document cannot be found, even though it previously indexed the document and a quick spot check shows the document to be in the correct place.
Can anyone shed some light on why VBA should display this behaviour?
The script is using the Dir$ function to index the files, and the Documents.Open function to open each word document for processing.
Sample code:
ChangeFileOpenDirectory (folderName)
inputFileName = Dir$(folderName & "*.doc")
Do While inputFileName <> ""
... call various functions here ...
inputFileName = Dir$
Loop
One of the functions called in the block has the following line:
Set currentDoc = Documents.Open(fileName:=docFileName, AddToRecentFiles:=False, Visible:=False)
This is the point at which the code is failing.
One of the most annoying things I have found is that recent files links are returned as the files themselves with Dir. You can use the FileSystemObject to check the file type.
I copy/paste your code and it works correctly.
However, it leaves all the files open (and hidden), and when you run it in another directory, additional files are opened and added to the open projects (take a look in the VBA editor).
My only guess is that after a while you're hitting the maximum allowable number of open files.
Try adding
currentdoc.Close
just before
inputFileName = Dir$
A few reasons, some duplicated from other answers:
If the path+ filename is long enough ... (you already answered in a comment)
If you are writing new files to same directory, Dir$ may get corrupted (happened to me)
If you have filenames with non-std chars (ex. "#")
Files locked by other processes
Files deleted while the macro is running
You may also try this code ...
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FileExists(file) Then ....
First enable the Microsoft Scripting reference in the VBE