vb check for specific file type in dir and perform code - vb.net

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

Related

How to get most recent modified date pdf file and display on VB from?

i'm trying to get vb to read the most recent modified pdf file in a specific folder and display the pdf file on my vb form. I only able to create a simple pdf display on my vb form and i'm stuck at this. Can anyone help?
Unable to find solution to my problem.
Dim testFile As System.IO.FileInfo
Dim fileName As String
Dim folderPath As String
Dim fullPath As String
testFile = My.Computer.FileSystem.GetFileInfo("C:\Users\example.pdf")
folderPath = testFile.DirectoryName
fileName = testFile.Name
fullPath = My.Computer.FileSystem.CombinePath(folderPath, fileName)
AxAcroPDF1.src = fullPath
my vb form should display the PDF based on the most recent modified file.
You can use the IO.DirectoryInfo class to get every IO.FileInfo in a directory while specifically targeting PDF files, then use LINQ to order them by their LastWriteTime, and then get the last file from the collection:
Dim folder As IO.DirectoryInfo = New IO.DirectoryInfo("my folder path here")
Dim lastModifiedPdf As IO.FileInfo = folder.GetFiles("*.pdf").OrderBy(Function(f) f.LastWriteTime).LastOrDefault()
If lastModifiedPdf IsNot Nothing Then
'....
End If
You need to call two sets of functions to achieve this.
A. Directory.GetFiles - this will list all the files in a directory, and it has options to provide a search pattern and also look in sub-folders.
B. File.GetLastWriteTime - this will return the last modified time of the file you pass to it.
You can put these functions together like:
Private Function GetLatestModifiedFileName(searchFolder As String) As String
Dim retVal = "<empty>"
Dim filesInDirectory() = Directory.GetFiles(searchFolder)
Dim latestModifiedtime As DateTime = DateTime.MinValue
For Each fileInDirectory As String In filesInDirectory
Dim currentFileModifiedTime As DateTime = File.GetLastWriteTime(fileInDirectory)
If (currentFileModifiedTime > latestModifiedtime) Then
retVal = fileInDirectory
latestModifiedtime = currentFileModifiedTime
End If
Next
Debug.Print("File: '{0}' was last modified on: '{1}'", retVal, latestModifiedtime)
Return retVal
End Function
and ultimately call this function using:
Dim lastModifiedFileName = GetLatestModifiedFileName("D:\Documents\")
The variable lastModifiedFileName will contain the full path to the file that has the latest modified date/time.

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

Get *only* file path of files without extension [vb.net]

I'm using a function to get the file paths in my executable path with the extension txt.
Dim FileEntries as string() = _
Directory.GetFiles(Path.GetDirectoryName(Application.ExecutablePath), "*txt"
But now i figures out that it would be better to use this files without the txt extension, despite the fact i can use notepad to change the lines anyway.
How do i use this function to get only the files without the extension?
If i use only "*" it gets all the files, apart from the extension. Thank you!
-EDIT-
I want to avoid any file that it's not suppose to be in the path. I want to gather only the files that have no extension, and therefore avoid any other file. If somehow a file is created there, with any extension, i want to avoid it.
You can use LINQ:
Dim nonTxtFiles =
From fn In Directory.EnumerateFiles(Path.GetDirectoryName(Application.ExecutablePath))
Where Not String.Equals(Path.GetExtension(fn), ".txt", Stringcomparison.InvariantCultureIgnoreCase)
Dim FileEntries as string() = nonTxtFiles.ToArray()
If you only want files without extensions(you have edited your question), it's easy:
Dim noExtFiles = From fn In Directory.EnumerateFiles(path)
Where String.IsNullOrEmpty(IO.Path.GetExtension(fn))
Another solution with Linq is to use the Path.GetExtension() method to see if the file has an extension:
Sub Main
Dim files = getFilenamesWithNoExtension("C:\SomeFolder")
End Sub
Private Function getFilenamesWithNoExtension(foldertosearch As String) As String()
Dim result As String()
result = Directory.EnumerateFiles(foldertosearch).Where(Function(f) String.IsNullOrEmpty(Path.GetExtension(f))).ToArray()
Return result
End Function

In vb.net, how do I get files from a directory based on a comma separated string?

I need to create an array() from files in a folder. Here's an example of how I would get all files within a folder.
Dim filesList = New DirectoryInfo("MyPath").GetFiles("*", SearchOption.TopDirectoryOnly).Where(Function(f) Not f.Attributes.HasFlag(FileAttributes.Hidden)).[Select](Function(f) New AClassNameHere(f)).ToArray()
I want to do the exact same thing, but only get files that exist in a comma separated string.
Dim myFiles as String = "filename1.jpg,filename2.jpg,filename3.jpg"
Where you see the AClassNameHere is a class I need to send each file to, and it would also be great if I knew how to send additional data about each file, like its type, size, etc.
Thank you kindly!
You could narrow the query results by adding an additional .Where() filter
Dim myFiles as String = "filename1.jpg,filename2.jpg,filename3.jpg"
Dim filesList = New DirectoryInfo("MyPath")
.GetFiles("*", SearchOption.TopDirectoryOnly)
.Where(Function(f) Not f.Attributes.HasFlag(FileAttributes.Hidden))
.Where(Function(f) myFiles.Contains(f.Name))
.[Select](Function(f) New AClassNameHere(f)).ToArray()
A better option would be to ensure that all filenames follow a pattern.
New DirectoryInfo("MyPath").GetFiles("filename*.jpg", SearchOption.TopDirectoryOnly)
Use this...
Dim Files() As String
Files= filesList.Split(",")
For each File In Files
Msgbox(File)
Next

How to get the file name of a file in VB?

I make a search program for searching a list of files in a computer and then copy the file into a store folder. The file name could be "*11*2.txt" As long as the program find this pattern, it should copy to the store folder. The problem is that I don't know the exactly name of the file before the search and I don't want to rename the file, I don't know how to save the file. Please help
I use the following to find the file, which does its work
Public Sub DirSearch(ByVal sDir As String, ByVal FileName As String)
Dim To_Path As String
To_Path = Form1.TextBox5.Text
For Each foundFile As String In My.Computer.FileSystem.GetFiles(sDir, FileIO.SearchOption.SearchAllSubDirectories, FileName)
Copy2Local(foundFile, To_Path)
Next
End Sub
Here is the current version of the Copy2Local (Note: it is not working right)
Public Sub Copy2Local(ByVal Copy_From_Path As String, ByVal Copy_To_Path As String)
' Specify the directories you want to manipulate.
Try
Dim fs As FileStream = File.Create(Copy_From_Path)
fs.Close()
' Copy the file.
File.Copy(Copy_From_Path, Copy_To_Path)
Catch
End Try
End Sub
First, you should check if ToPath is a valid directory since it's coming from a TextBox:
Dim isValidDir = Directory.Exists(ToPath)
Second, you can use Path.Combine to create a path from separate (sub)directories or file-names:
Dim copyToDir = Path.GetDirectoryName(Copy_To_Path)
Dim file = Path.GetFileName(Copy_From_Path)
Dim newPath = Path.Combine(copyToDir, file)
http://msdn.microsoft.com/en-us/library/system.io.path.aspx
(disclaimer: typed from a mobile)
To answer your question: You can get the file name with Path.GetFileName. Example:
Dim fileName As String = Path.GetFileName(foundFile)
However, there's a bunch of other things wrong with your code:
Here,
Dim fs As FileStream = File.Create(Copy_From_Path)
fs.Close()
you are overwriting your source file. This does not seem like a good idea. ;-)
And here,
Try
...
Catch
' Do Nothing
End Try
You are throwing away exceptions that would help you find and diagnose problems. Don't do that. It makes debugging a nightmare.
In vb.net, I'm using the following code to find the filename
Textbox1.Text = New FileInfo(OpenFileDialog.FileName).Name
this code work fine with open file dialog box