Get only those files in a directory whose name does not start with a certain string - vb.net

I currently have this code:
Dim FolderInfo As IO.DirectoryInfo = New IO.DirectoryInfo("C:\Scratch")
For Each FInfo As IO.FileInfo In FolderInfo.GetFiles("*.xlsx")
MessageBox.Show(FInfo.ToString())
Next FInfo
Obviously this will get all the files that match the pattern "*.xlsx" - but I am NOT interested in any files that start with "old" - so of course within the For Next, I could do something like if If Not FInfo.Name.StartsWith("old") Then ... and do what I need to do, but I was wondering if there is any way to tell the GetFiles to only get files that "don't start with "old" and end in *.xlsx" ?
I've seen examples in C# that I believe use LINQ - so after the GetFiles there is stuff like ".Where(f => !(f.FullName.StartsWith("old")))" but not sure what ( if there is one ) the equivilant would be for VB.NET ?
Cheers,
Chris.

The syntax is a bit more verbose, but Where works as well in VB
For Each FInfo As IO.FileInfo In FolderInfo.GetFiles("*.xlsx").
Where(Function(x) Not x.Name.StartsWith("old"))
MessageBox.Show(FInfo.ToString())
Next FInfo
I would also add a StringComparison.CurrentCultureIgnoreCase to remove also files that starts with "Old" or "OLD" and so on
For Each FInfo As IO.FileInfo In FolderInfo.GetFiles("*.xlsx").
Where(Function(x) Not x.Name.StartsWith("old", StringComparisong.CurrentCultureIgnoreCase))
MessageBox.Show(FInfo.ToString())
Next FInfo
By the way, you should use the property Name instead of FullName. FullName returns also the path to the file and, obviously, this path doesn't start with "old".

Dim folder As String = "C:\Scratch"
Dim files = Directory.EnumerateFiles(folder, "*.xlsx", SearchOption.TopDirectoryOnly) _
.Where(Function(f) Not Path.GetFileName(f).ToLowerInvariant().StartsWith("old"))
For Each file As string In files
MessageBox.Show(file)
Next file

Related

Delete A File That Contains The App Name (VB.NET)

This is the code I'm Using:
Dim file As String
Dim prefetchPath As String
Dim FileName As String = My.Application.Info.AssemblyName
prefetchPath = Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine) & "\Prefetch"
For Each file In IO.Directory.GetFiles(prefetchPath)
If file.Contains(FileName) Then
IO.File.Delete(file)
End If
Next
i don't know why it does not work if i use FileName. But it work if i use this code
If file.Contains("Example.exe") Then
IO.File.Delete(file)
End If
I want to make sure that if someone changes the name of the application the code works the same way(I already running the file as Administrator)
Help me Thanks.
My guess is that AssemblyName only returns the name without the extension, try including the .exe. Also, it is worth noting that you can use the IO.DirectoryInfo class and pass the file name in the GetFiles method to cut out your For/Each loop.
Here is a quick example:
Dim prefetchPath As String = IO.Path.Combine(Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine), "Prefetch")
Dim FileName As String = My.Application.Info.AssemblyName & ".exe"
If New IO.DirectoryInfo(prefetchPath).GetFiles(FileName).Count > 0 Then
IO.File.Delete(IO.Path.Combine(prefetchPath, FileName))
End If

vb check for specific file type in dir and perform code

I'm trying to make a program that checks for specific file type in a directory, then executes a code if there are any files of that type found.
I'm assuming something like this:
For Each foundFile As String In
My.Computer.FileSystem.GetFiles(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
(If any found files are, for example, "txt" files, then display their content.)
Next
Thanks in advance.
You can use Directory.GetFiles or Directory.EnumerateFiles with a parameter for the extension-filter:
Dim directoryPath = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Dim allTxtFiles = Directory.EnumerateFiles(directoryPath, ".txt")
For each file As String In allTxtFiles
Console.WriteLine(file)
Next
The difference between both methods is that the first returns a String(), so loads all into memory immediately whereas the second returns a "query". If you want to use LINQ it's better to use EnumerateFiles, f.e. if you want to take the first 10 files:
Dim firstTenFiles As List(Of String) = allTxtFiles.Take(10).ToList()
Dim di As DirectoryInfo = New DirectoryInfo(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
For Each fi In di.GetFiles("*.txt")
Dim content As String = My.Computer.FileSystem.ReadAllText(fi.FullName)
Console.WriteLine(fi.Name)
Next

VB Getting The SubFolder name and saving it to a Text file

I want to get The Subfolder Name Listed in my Textfile.
I don't want to see the path for the SubFolder.
I finally got a way to show only to my VS Console. But If i try to save it to my txt file it keeps on writing only the first line even though I used For. Please Help Me!
Here's the code that writes to the console
Dim di As New IO.DirectoryInfo(startPath)
Dim Drs() As IO.DirectoryInfo = di.GetDirectories()
For Each dr As IO.DirectoryInfo In Drs
Console.WriteLine(dr.Name)
Next
This is the code that I tried to Write It on a txt file. It only writes 1 Line
For Each Dir As String In Directory.GetDirectories(startPath)
My.Computer.FileSystem.WriteAllText("C:\Test.txt", Dir, False)
Next
The Expected Output is
SubFolder1
SubFolder2
SubFolder3
SubFolder4
SubFolder5
Like this in txt file
You are using the wrong method, WriteAllText always overwrites the complete file, you want to append a new line. You could use File.AppendAllText:
For Each Dir As String In Directory.GetDirectories(startPath)
System.IO.File.AppendAllText("C:\Test.txt", Dir)
Next
Another option, use a StreamWriter, it has a constructor that takes a Boolean to append text:
Using writer As New System.IO.StreamWriter(startPath, True)
For Each Dir As String In Directory.GetDirectories(startPath)
writer.WriteLine(Dir)
Next
End Using

Get files in a directory not containing certain pattern with FileInfo object

I have this files in a directory:
User1_File1.pdf
User1_File2.pdf
User1_File2-1.pdf
User1_File2-2.pdf
User1_File3.pdf
User1_File4.pdf
I'm working in vb .Net. Using the GetFiles method of the FileInfo object I want to get all the files NOT containing the "-" character in the name. How can I do this?
Dim diDirectorio As New DirectoryInfo(sPath)
Dim fiArchivos() As FileInfo = diDirectorio.GetFiles(sFilter & "*.*")
If Not fileName.Contains("-") Then
'Get code
End If
Post your code and I can implement this feature for you.
I know that this is old now but this works too...
dim dirInfo as new io.DirectoryInfo("DirectoryPath")
dim files as io.fileinfo() = dirInfo.GetFiles("pattern").Where(Function(x) Not x.Name.ToLower.Contains("exclude pattern")).toArray

How to find or get files in Directory with Specific word in the file name Visual Basic.net?

I need to get files from a directory containing specific characters in it's name:
The following code below will return any file with the .csv extension. The problem is there are other csv file I need to leave alone or not get.
Dim FileLocation As DirectoryInfo = _
New DirectoryInfo("C:\Folder\Subfolder\Data\Input\")
Dim fi As FileInfo() = FileLocation.GetFiles("*.csv")
Instead of getting any csv file, I would like to get a file with the word data, so any file name containing the word data. Example: *my_data_file.csv*
How do I do this with the code above?
You can update the filter with the string you want to account for (caps will automatically be taken care of):
Dim fi As FileInfo() = FileLocation.GetFiles("*data*.csv")
In any case, bear in mind that this filtering is not "too accurate". For example, the code above would also account for any file (including "data"), whose extension includes csv (e.g., *.csva, *.csvb, etc.). If you want a 100%-reliable approach you should better set up a loop and carry out the filtering "manually"; loops are pretty fast and you wouldn't even notice the difference.
Example of a loop:
Dim fi As List(Of FileInfo) = New List(Of FileInfo)
For Each File In FileLocation.GetFiles()
If (File IsNot Nothing) Then
If (Path.GetExtension(File.ToString.ToLower) = ".csv") Then
If (File.ToString.ToLower.Contains("data")) Then fi.Add(File)
End If
End If
Next
This code will work for sure under your exact requirements and might take care of more complex requests. I have accounted for a List just to show the point clearer.
If you can use LINQ extensions then you can do it this way:
' Get Files {directory} {recursive} {ext} {word in filename}
Private Function Get_Files(ByVal directory As String, _
ByVal recursive As IO.SearchOption, _
ByVal ext As String, _
ByVal with_word_in_filename As String) As List(Of IO.FileInfo)
Return IO.Directory.GetFiles(directory, "*" & If(ext.StartsWith("*"), ext.Substring(1), ext), recursive) _
.Where(Function(o) o.ToLower.Contains(with_word_in_filename.ToLower)) _
.Select(Function(p) New IO.FileInfo(p)).ToList
End Function
Usage example:
For Each file As IO.FileInfo In Get_Files("C:\Folder\Subfolder\Data\Input\", _
IO.SearchOption.TopDirectoryOnly, _
"csv", _
"data")
MsgBox(file.Name)
Next
Replace the wildcard search below "." with your search criteria, for example you want all files that start with name "Hospital*"
Dim Folder As New IO.DirectoryInfo("C:\SampleFolder")
For Each File as IO.FileInfo in Folder.GetFiles("*.*",IO.SearchOption.AllDirectories)
ListBox1.Items.Add(File.FullName)
Next
I would have added this as a comment to the accepted answer, but I do not have enough points to do so:
I just wanted to add varocarbas's answer that, if anyone was wondering (as I was) if this would work in a web scenario as well, it will. Just place the web path inside Server.MapPath() like this:
Dim FileLocation As DirectoryInfo =
New DirectoryInfo(Server.MapPath("/Folder/SubFolder/Data/Input/"))
NOTE: Will NOT work with full url's (no 'http://www.123.com').
Dim Folder As New IO.DirectoryInfo("C:\SampleFolder")
For Each File as IO.FileInfo in Folder.GetFiles("*.*",IO.SearchOption.AllDirectories)
ListBox1.Items.Add(File.FullName)
Application.DoEvents()
Next