Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Get list of word ducuments in a folder

Posted on 2016-12-01
10
Medium Priority
?
62 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 3
10 Comments
 
LVL 85

Accepted Solution

by:
Scott McDaniel (Microsoft Access MVP - EE MVE ) earned 1000 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 34

Assisted Solution

by:it_saige
it_saige earned 1000 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
Interactive Way of Training for the AWS CSA Exam

An interactive way of learning that will help you visualize core concepts so that you can be more effective when taking your AWS certification exam.  Built for students by a student to help them understand the concepts that they are being taught.

 

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 34

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 34

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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
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…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

722 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