Solved

Get list of word ducuments in a folder

Posted on 2016-12-01
10
42 Views
Last Modified: 2016-12-01
Hello,
How can I get list of all the word documents in a folder and get the list ota listbox.

The word doument is in format
Microsoft Word 97 - 2003 Document (.doc)
But want the code to pick up any  word format example .docx etc.

Cheers
0
Comment
Question by:RIAS
  • 6
  • 3
10 Comments
 
LVL 84

Accepted Solution

by:
Scott McDaniel (Microsoft Access MVP - EE MVE ) earned 250 total points
ID: 41908772
I'm sure there are other ways, but I like to store the filename/path in a Data table and then bind the listbox (or grid) to that datatable:

Dim dir As New IO.DirectoryInfo(txInboundDocumentPath.Text)
Dim fils As IO.FileInfo() = dir.GetFiles("*.txt")
Dim f As IO.FileInfo

Dim dt As New DataTable
Dim col As New DataColumn() With {.ColumnName = "Select", .DataType = GetType(Boolean)}
dt.Columns.Add(col)
col = New DataColumn With {.ColumnName = "FileName", .DataType = GetType(String), .Caption = "File Name"}
dt.Columns.Add(col)

For Each f In fils
	Dim dtrn As DataRow = dt.NewRow
	dtrn("FileName") = f.FullName
	dt.Rows.Add(dtrn)
Next

dgInvoices.DataSource = dt

Open in new window


You'd change this line to filter for the extensions:

Dim fils As IO.FileInfo() = dir.GetFiles("*.txt")

Perhaps:

Dim fils As IO.FileInfo() = dir.GetFiles("*.doc;*.docx")
0
 
LVL 33

Assisted Solution

by:it_saige
it_saige earned 250 total points
ID: 41908785
By using the Directory.GetFiles (or Directory.EnumerateFiles) method that accepts a filter; e.g. -
Imports System.IO

Module Module1
	Sub Main()
		GetFiles("C:\_admin\")
		Console.WriteLine()
		EnumerateFiles("C:\_admin\")
		Console.ReadLine()
	End Sub

	Private Sub GetFiles(ByVal path As String)
		Console.WriteLine("Listing files that match the filter *.doc? but using the GetFiles method")
		For Each [file] In Directory.GetFiles(path, "*.doc?", SearchOption.AllDirectories)
			Console.WriteLine([file])
		Next
	End Sub

	Private Sub EnumerateFiles(ByVal path As String)
		Console.WriteLine("Listing files that match the filter *.doc? but using the EnumerateFiles method")
		For Each [file] In Directory.EnumerateFiles(path, "*.doc?", SearchOption.AllDirectories)
			Console.WriteLine([file])
		Next
	End Sub
End Module

Open in new window

Produces the following sample output -Capture.JPG
-saige-
0
 

Author Closing Comment

by:RIAS
ID: 41908801
Thanks you Scott and Saige Sir!
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

Author Comment

by:RIAS
ID: 41908817
Hello Scott,

Tried you r solution :
 dtrn("FileName") = f.FullName

this gives fullname with the path.
How can I get only the document name and not the path as the prefix.

Cheers
0
 
LVL 33

Expert Comment

by:it_saige
ID: 41908819
Putting this into a windows form example application:

Form1.vb -
Imports System.ComponentModel
Imports System.IO

Public Class Form1
	Private Sub OnLoad(sender As Object, e As EventArgs) Handles MyBase.Load
		GetWorker.RunWorkerAsync("C:\_admin\")
		EnumerateWorker.RunWorkerAsync("C:\_admin\")
	End Sub

	Private Sub OnDoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles GetWorker.DoWork, EnumerateWorker.DoWork
		If TypeOf sender Is BackgroundWorker Then
			Dim worker = DirectCast(sender, BackgroundWorker)
			Dim [path] As String = If(e.Argument IsNot Nothing AndAlso Not String.IsNullOrWhiteSpace(e.Argument), e.Argument, New DirectoryInfo(Application.ExecutablePath).Root)
			If worker.Equals(GetWorker) Then
				For Each [file] In Directory.GetFiles([path], "*.doc?", SearchOption.AllDirectories)
					worker.ReportProgress(0, [file])
				Next
			ElseIf worker.Equals(EnumerateWorker) Then
				For Each [file] In Directory.EnumerateFiles([path], "*.doc?", SearchOption.AllDirectories)
					worker.ReportProgress(0, [file])
				Next
			End If
		End If
	End Sub

	Private Sub OnProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles GetWorker.ProgressChanged, EnumerateWorker.ProgressChanged
		If TypeOf sender Is BackgroundWorker Then
			Dim worker = DirectCast(sender, BackgroundWorker)
			Dim [file] As String = If(e.UserState IsNot Nothing AndAlso Not String.IsNullOrWhiteSpace(e.UserState), e.UserState, Nothing)
			If [file] IsNot Nothing Then
				If worker.Equals(GetWorker) Then
					GetListBox.Items.Add([file])
				ElseIf worker.Equals(EnumerateWorker) Then
					EnumerateListBox.Items.Add([file])
				End If
			End If
		End If
	End Sub
End Class

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
		Me.GetListBox = New System.Windows.Forms.ListBox()
		Me.EnumerateListBox = New System.Windows.Forms.ListBox()
		Me.Label1 = New System.Windows.Forms.Label()
		Me.Label2 = New System.Windows.Forms.Label()
		Me.GetWorker = New System.ComponentModel.BackgroundWorker()
		Me.EnumerateWorker = New System.ComponentModel.BackgroundWorker()
		Me.SuspendLayout()
		'
		'GetListBox
		'
		Me.GetListBox.FormattingEnabled = True
		Me.GetListBox.Location = New System.Drawing.Point(13, 30)
		Me.GetListBox.Name = "GetListBox"
		Me.GetListBox.Size = New System.Drawing.Size(275, 342)
		Me.GetListBox.TabIndex = 0
		'
		'EnumerateListBox
		'
		Me.EnumerateListBox.FormattingEnabled = True
		Me.EnumerateListBox.Location = New System.Drawing.Point(297, 29)
		Me.EnumerateListBox.Name = "EnumerateListBox"
		Me.EnumerateListBox.Size = New System.Drawing.Size(275, 342)
		Me.EnumerateListBox.TabIndex = 1
		'
		'Label1
		'
		Me.Label1.AutoSize = True
		Me.Label1.Location = New System.Drawing.Point(13, 13)
		Me.Label1.Name = "Label1"
		Me.Label1.Size = New System.Drawing.Size(78, 13)
		Me.Label1.TabIndex = 2
		Me.Label1.Text = "Using GetFiles:"
		'
		'Label2
		'
		Me.Label2.AutoSize = True
		Me.Label2.Location = New System.Drawing.Point(297, 13)
		Me.Label2.Name = "Label2"
		Me.Label2.Size = New System.Drawing.Size(112, 13)
		Me.Label2.TabIndex = 3
		Me.Label2.Text = "Using EnumerateFiles:"
		'
		'GetWorker
		'
		Me.GetWorker.WorkerReportsProgress = True
		'
		'EnumerateWorker
		'
		Me.EnumerateWorker.WorkerReportsProgress = True
		'
		'Form1
		'
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(584, 383)
		Me.Controls.Add(Me.Label2)
		Me.Controls.Add(Me.Label1)
		Me.Controls.Add(Me.EnumerateListBox)
		Me.Controls.Add(Me.GetListBox)
		Me.Name = "Form1"
		Me.Text = "Form1"
		Me.ResumeLayout(False)
		Me.PerformLayout()

	End Sub
	Friend WithEvents GetListBox As System.Windows.Forms.ListBox
	Friend WithEvents EnumerateListBox As System.Windows.Forms.ListBox
	Friend WithEvents Label1 As System.Windows.Forms.Label
	Friend WithEvents Label2 As System.Windows.Forms.Label
	Friend WithEvents GetWorker As System.ComponentModel.BackgroundWorker
	Friend WithEvents EnumerateWorker As System.ComponentModel.BackgroundWorker

End Class

Open in new window

Produces the following sample output -Capture.JPG
-saige-
1
 

Author Comment

by:RIAS
ID: 41908821
Saige Sir,
But,again it has filepath with it.
Just need a dropdown with name of the documents.

Thanks
0
 

Author Comment

by:RIAS
ID: 41908829
Hello Scott,

Found it :

 dtrn("FileName") = f.FullName
0
 

Author Comment

by:RIAS
ID: 41908831
Saige Sir,
Thank you for pointing to background worker,really needed something with the async threading.

Cheers
0
 
LVL 33

Expert Comment

by:it_saige
ID: 41908838
If you don't want to include the path portion, you can do one of two things, SubString based on the last index of the '\' character; e.g. -
Dim output = [file].Substring([file].LastIndexOf("\") + 1))

Open in new window

Or
You can use a FileInfo object to just get the filename; e.g. -
Dim output = New FileInfo([file]).Name

Open in new window


Putting those changes into effect in both applications:

Console Application -
Imports System.IO

Module Module1
	Sub Main()
		GetFiles("C:\_admin\")
		Console.WriteLine()
		EnumerateFiles("C:\_admin\")
		Console.ReadLine()
	End Sub

	Private Sub GetFiles(ByVal path As String)
		Console.WriteLine("Listing files that match the filter *.doc? but using the GetFiles method")
		For Each [file] In Directory.GetFiles(path, "*.doc?", SearchOption.AllDirectories)
			Console.WriteLine([file].Substring([file].LastIndexOf("\") + 1))
		Next
	End Sub

	Private Sub EnumerateFiles(ByVal path As String)
		Console.WriteLine("Listing files that match the filter *.doc? but using the EnumerateFiles method")
		For Each [file] In Directory.EnumerateFiles(path, "*.doc?", SearchOption.AllDirectories)
			Console.WriteLine(New FileInfo([file]).Name)
		Next
	End Sub
End Module

Open in new window

Sample output -Capture.JPG
Form Application -

Form1.vb -
Imports System.ComponentModel
Imports System.IO

Public Class Form1
	Private Sub OnLoad(sender As Object, e As EventArgs) Handles MyBase.Load
		GetWorker.RunWorkerAsync("C:\_admin\")
		EnumerateWorker.RunWorkerAsync("C:\_admin\")
	End Sub

	Private Sub OnDoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles GetWorker.DoWork, EnumerateWorker.DoWork
		If TypeOf sender Is BackgroundWorker Then
			Dim worker = DirectCast(sender, BackgroundWorker)
			Dim [path] As String = If(e.Argument IsNot Nothing AndAlso Not String.IsNullOrWhiteSpace(e.Argument), e.Argument, New DirectoryInfo(Application.ExecutablePath).Root)
			If worker.Equals(GetWorker) Then
				For Each [file] In Directory.GetFiles([path], "*.doc?", SearchOption.AllDirectories)
					worker.ReportProgress(0, [file].Substring([file].LastIndexOf("\") + 1))
				Next
			ElseIf worker.Equals(EnumerateWorker) Then
				For Each [file] In Directory.EnumerateFiles([path], "*.doc?", SearchOption.AllDirectories)
					worker.ReportProgress(0, New FileInfo([file]).Name)
				Next
			End If
		End If
	End Sub

	Private Sub OnProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles GetWorker.ProgressChanged, EnumerateWorker.ProgressChanged
		If TypeOf sender Is BackgroundWorker Then
			Dim worker = DirectCast(sender, BackgroundWorker)
			Dim [file] As String = If(e.UserState IsNot Nothing AndAlso Not String.IsNullOrWhiteSpace(e.UserState), e.UserState, Nothing)
			If [file] IsNot Nothing Then
				If worker.Equals(GetWorker) Then
					GetListBox.Items.Add([file])
				ElseIf worker.Equals(EnumerateWorker) Then
					EnumerateListBox.Items.Add([file])
				End If
			End If
		End If
	End Sub
End Class

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
		Me.GetListBox = New System.Windows.Forms.ListBox()
		Me.EnumerateListBox = New System.Windows.Forms.ListBox()
		Me.Label1 = New System.Windows.Forms.Label()
		Me.Label2 = New System.Windows.Forms.Label()
		Me.GetWorker = New System.ComponentModel.BackgroundWorker()
		Me.EnumerateWorker = New System.ComponentModel.BackgroundWorker()
		Me.SuspendLayout()
		'
		'GetListBox
		'
		Me.GetListBox.FormattingEnabled = True
		Me.GetListBox.Location = New System.Drawing.Point(13, 30)
		Me.GetListBox.Name = "GetListBox"
		Me.GetListBox.Size = New System.Drawing.Size(275, 342)
		Me.GetListBox.TabIndex = 0
		'
		'EnumerateListBox
		'
		Me.EnumerateListBox.FormattingEnabled = True
		Me.EnumerateListBox.Location = New System.Drawing.Point(297, 29)
		Me.EnumerateListBox.Name = "EnumerateListBox"
		Me.EnumerateListBox.Size = New System.Drawing.Size(275, 342)
		Me.EnumerateListBox.TabIndex = 1
		'
		'Label1
		'
		Me.Label1.AutoSize = True
		Me.Label1.Location = New System.Drawing.Point(13, 13)
		Me.Label1.Name = "Label1"
		Me.Label1.Size = New System.Drawing.Size(78, 13)
		Me.Label1.TabIndex = 2
		Me.Label1.Text = "Using GetFiles:"
		'
		'Label2
		'
		Me.Label2.AutoSize = True
		Me.Label2.Location = New System.Drawing.Point(297, 13)
		Me.Label2.Name = "Label2"
		Me.Label2.Size = New System.Drawing.Size(112, 13)
		Me.Label2.TabIndex = 3
		Me.Label2.Text = "Using EnumerateFiles:"
		'
		'GetWorker
		'
		Me.GetWorker.WorkerReportsProgress = True
		'
		'EnumerateWorker
		'
		Me.EnumerateWorker.WorkerReportsProgress = True
		'
		'Form1
		'
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(584, 383)
		Me.Controls.Add(Me.Label2)
		Me.Controls.Add(Me.Label1)
		Me.Controls.Add(Me.EnumerateListBox)
		Me.Controls.Add(Me.GetListBox)
		Me.Name = "Form1"
		Me.Text = "Form1"
		Me.ResumeLayout(False)
		Me.PerformLayout()

	End Sub
	Friend WithEvents GetListBox As System.Windows.Forms.ListBox
	Friend WithEvents EnumerateListBox As System.Windows.Forms.ListBox
	Friend WithEvents Label1 As System.Windows.Forms.Label
	Friend WithEvents Label2 As System.Windows.Forms.Label
	Friend WithEvents GetWorker As System.ComponentModel.BackgroundWorker
	Friend WithEvents EnumerateWorker As System.ComponentModel.BackgroundWorker

End Class

Open in new window

Sample output -Capture.JPG
-saige-
1
 

Author Comment

by:RIAS
ID: 41908843
Thank you so much Sir, for the efforts.
0

Featured Post

How our DevOps Team Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to sort a list of objects using an item in an enclosed list 5 48
vb.net help 4 31
Alert on Server memory 2 26
Help with consolidating excel files using VB.net 2 26
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

825 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question