Solved

Get list of word ducuments in a folder

Posted on 2016-12-01
10
13 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
Comment Utility
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 32

Assisted Solution

by:it_saige
it_saige earned 250 total points
Comment Utility
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
Comment Utility
Thanks you Scott and Saige Sir!
0
 

Author Comment

by:RIAS
Comment Utility
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 32

Expert Comment

by:it_saige
Comment Utility
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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

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

Thanks
0
 

Author Comment

by:RIAS
Comment Utility
Hello Scott,

Found it :

 dtrn("FileName") = f.FullName
0
 

Author Comment

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

Cheers
0
 
LVL 32

Expert Comment

by:it_saige
Comment Utility
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
Comment Utility
Thank you so much Sir, for the efforts.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

763 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now