display all excel file in folder - vb.net

I want to review all the Excel files inside a folder to listbox, noting that the Excel includes more than one version.
I used the following code and it didn't work
Dim di As New IO.DirectoryInfo("D:\EXCEL")
Dim aryFi As IO.FileInfo() = di.GetFiles("Excel Worksheets|*.xls; *.xlsx; *.xlsm")
Dim fi As IO.FileInfo
For Each fi In aryFi
ListBox1.Items.Add((fi))
Next

Modified slightly from this example: https://stackoverflow.com/a/3527717/1920035
Private Function GetExcelFiles(ByVal directoryInfo As IO.DirectoryInfo) As IO.FileInfo()
If (directoryInfo Is Nothing) Then
Throw New ArgumentNullException(NameOf(directoryInfo))
End If
Dim files As IEnumerable(Of IO.FileInfo) = directoryInfo.GetFiles()
Dim excelFileExtensions() As String = {".xlsx", ".xlsm", ".xlsb", ".xltm", ".xlam", ".xls", ".xla", ".xlb", ".xlc", ".xld", ".xlk", ".xll", ".xlm", ".xlt", ".xlv", ".xlw"}
return files.Where(Function(file) excelFileExtensions.Contains(file.Extension))
End Function
What this does is:
Get all files from the directory info
Declare a collection of file extensions to check against
Return only the files where the extension exists in the file extensions collection
Important to note - It may be worthwhile moving the excelFileExtensions so that it is a private readonly variable at a higher scope. It isn't much, but if you're running this a lot then it will make a difference.

Related

Iterate through a directory to get subfolders and certain files

I am working on a program that will move files to a database, text files to be exact. The user will have a starting directory and inside will multiple sub folders and files and so on. I want to go through each Folder and sub folder looking for the text files and add them accordingly to the database so it resembles a directory structure in a way. In the program the files are organized such as the folders are "Categories" that are displayed into a tree view.I am only adding the folder names(as Categories) that do contain text files and their subs and so forth. As well I need to figure out where to plug in the adding of the "Category". As of right now I am using a couple of listboxes for my output until I can get it all figured out.
lstfiles.Items.Add(Dir)
For Each file In System.IO.Directory.GetFiles(Dir)
Dim fi As System.IO.FileInfo = New IO.FileInfo(file)
If fi.Extension = ".txt" Then
If lstRootFolderFiles.Items.Contains(file) = False Then
lstfiles.Items.Add(file)
AddFile(file, Gennumber(9999))
End If
End If
Next
For Each folder In System.IO.Directory.GetDirectories(Dir)
lstfiles.Items.Add(folder)
For Each file In System.IO.Directory.GetFiles(folder)
Dim fi As System.IO.FileInfo = New IO.FileInfo(file)
If fi.Extension = ".txt" Then
If lstRootFolderFiles.Items.Contains(file) = False Then
lstfiles.Items.Add(file)
End If
End If
Next
Next
I have gotten so far as to iterate through the directory and get files but it returns folders that are empty. And I need to figure out where I need to put in my addcategory function. And also remember the last one that was added so they can be added as a subcategory.
I think I am making a big mess of it all, or over thinking the whole thing.
Any assistance or guidance would be appreciated.Thank you
The end result that I came up with was much different from my original posting, as it was my way of thinking of how it was going to work. I split up the two main functions. Retrieving the Folders and retrieving the files.
DirEx is the Import Directory, CatID is the Tag of the selected Treenode where the folders are going to added in.
Private Sub DirImport_GetSubDirectories(ByVal DirEx As String, ByVal CatID As Integer)
Try
Dim ClsData As New clsNoteData
'Set the DatabaseFile Property of the class
ClsData.Database = LoadedLibraryDatabase
' Get all subdirectories
Dim subdirectoryEntries() As String = Directory.GetDirectories(DirEx)
' Loop through them to see if they have any other subdirectories
Dim subdirectory As String
For Each subdirectory In subdirectoryEntries
'If the Directory is not Empty
If Not Directory.GetFileSystemEntries(subdirectory).Length = 0 Then
Dim di As DirectoryInfo = New DirectoryInfo(subdirectory)
'Creating Random Number
Dim NewCatID As Integer = GenNumber(9999)
'Call for a new Sub Category
ClsData.NewSubCategoryNode(LoadedLibraryDatabase, NewCatID, CatID, di.Name, -1)
'Get files in the current Directory
DirImport_GetFiles(subdirectory, NewCatID)
'Get the next set of Subfolders
DirImport_GetSubDirectories(subdirectory, NewCatID)
End If
Next
Catch ex As Exception
End Try
End Sub
Private Sub DirImport_GetFiles(ByVal DirEx As String, ByVal CatID As Integer)
Dim Files() As String = Directory.GetFiles(DirEx, "*.txt")
Dim file As String
For Each file In Files
Dim clsNoteData As New clsNoteData
Dim fi As FileInfo = New FileInfo(file)
clsNoteData.Database = LoadedLibraryDatabase
clsNoteData.NewNote_ID = GenNumber(99999)
clsNoteData.NewNote_CatID = CatID
clsNoteData.NewNote_Title = Path.GetFileNameWithoutExtension(file)
clsNoteData.NewNote(False, file)
Next
End sub
So here it is for anyone who may want to do something similar.

Get only those files in a directory whose name does not start with a certain string

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

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

VB 2010: How to copy all subfolders of a folder to another folder?

I got a question in Visual Basic 2010: How can I copy all subfolders (only the subfolders, not the main folder) into another folder?
You need to recursively iterate through all the files and folders and copy them. This method should do the job for you:
Public Sub CopyDirectory(ByVal sourcePath As String, ByVal destinationPath As String)
Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(sourcePath)
' If the destination folder don't exist then create it
If Not System.IO.Directory.Exists(destinationPath) Then
System.IO.Directory.CreateDirectory(destinationPath)
End If
Dim fileSystemInfo As System.IO.FileSystemInfo
For Each fileSystemInfo In sourceDirectoryInfo.GetFileSystemInfos
Dim destinationFileName As String =
System.IO.Path.Combine(destinationPath, fileSystemInfo.Name)
' Now check whether its a file or a folder and take action accordingly
If TypeOf fileSystemInfo Is System.IO.FileInfo Then
System.IO.File.Copy(fileSystemInfo.FullName, destinationFileName, True)
Else
' Recursively call the mothod to copy all the neste folders
CopyDirectory(fileSystemInfo.FullName, destinationFileName)
End If
Next
End Sub
System.IO has two classes that you can use in a recursive fashion to do this all from code.
DirectoryInfo
FileInfo
DirectoryInfo has two methods that are relevant:
GetDirectories
GetFiles
FileInfo has a CopyTo method
Given those objects and methods and a bit of creative recursion you should be able to copy the stuff fairly easily.
This seems to be the simplest solution:
For Each oDir In (New DirectoryInfo("C:\Source Folder")).GetDirectories()
My.Computer.FileSystem.CopyDirectory(oDir.FullName, "D:\Destination Folder", overwrite:=True)
Next oDir
1 Line:
My.Computer.FileSystem.CopyDirectory(txtSourceDirectory.Text, txtDestinationDirectory.Text, True)

how to check if ANY directory exists without knowing a specific directory name, but rather just the folder that the folder might be in

In vb.net how do you check if a ANY directory exists inside a directory
I would need to know if there is a folder inside the c:\windows directory (WITHOUT knowing if there is ANY directory is in there).
So you want to check to see if there are subdirectories in a directory? Fair enough:
Dim hasSubDirectories as Boolean = My.Computer.FileSystem.GetDirectories(parentDir).Count > 0
You can use the DirectoryInfo class inside the System.IO namespace.
Example:
Dim path As String = "C:\Windows"
Dim directoryInfo As New DirectoryInfo(path)
Dim dirInfos() As DirectoryInfo = directoryInfo.GetDirectories()
If (dirInfos.Length > 0) Then
' you have directories, do what you want
End If
'or iterate over directories
For Each dirInfo As DirectoryInfo In dirInfos
' do something with each directory
Next
Rather than use a VB-specific function like mattbasta suggests, it's just as easy to use the System.IO.Directory class, which is part of the BCL and would be familiar to any other .NET developer.
Dim hasSubDirectories = System.IO.Directory.GetDirectories(parentPath).Length > 0
Problem is that i cant convert to string
Dim path As String = "..\..\..\Tier1 downloads\CourseVB\"
If countNumberOfFolders > 0 Then 'if there is a folder then
' make a reference to a directory
Dim di As New IO.DirectoryInfo(path)
Dim diar1 As IO.DirectoryInfo() = di.GetDirectories()
Dim dra As IO.DirectoryInfo
'list the names of all files in the specified directory
For Each dra In diar1
Dim lessonDirectoryName() As Lesson
lessonDirectoryName(0).lessonName = dra
Next
'the the lesson is an object, and lessonName is the property of type string. How do i convert the directoryInfo to string?