• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 73
  • Last Modified:

Get list of word ducuments in a folder

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
RIAS
Asked:
RIAS
  • 6
  • 3
2 Solutions
 
Scott McDaniel (Microsoft Access MVP - EE MVE )Infotrakker SoftwareCommented:
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
 
it_saigeDeveloperCommented:
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
 
RIASAuthor Commented:
Thanks you Scott and Saige Sir!
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
RIASAuthor Commented:
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
 
it_saigeDeveloperCommented:
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
 
RIASAuthor Commented:
Saige Sir,
But,again it has filepath with it.
Just need a dropdown with name of the documents.

Thanks
0
 
RIASAuthor Commented:
Hello Scott,

Found it :

 dtrn("FileName") = f.FullName
0
 
RIASAuthor Commented:
Saige Sir,
Thank you for pointing to background worker,really needed something with the async threading.

Cheers
0
 
it_saigeDeveloperCommented:
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
 
RIASAuthor Commented:
Thank you so much Sir, for the efforts.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

  • 6
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now