Get a list of files from a Directory

I am looking to get a list of documents withing a specific directory Directory.GetFiles(“address”).

This is giving me the complete file name but cannot figure how to get this broken down to the individual document names

4 Likes

for each item in Directory.GetFiles(“address”)

4 Likes

Thanks for the quick reply theo500. I have already tried this however the output gives me the full address for the document (inc the document name) i.e “C:\users\documents\test1.xls”. I would like the output to only include the document name i.e. “test1.xls”

1 Like

you will need another variable declared of type System.IO.FileInfo and assign the item from the loop

pseudo code

for each item in directory.getfiles()
myFileInfoVar = new FileInfo(item)
messagebox myFileInfoVar.Name

8 Likes

Thank you for the quick reply, I certainly appreciate the help

I am receiving a compiler error of the system.IO.fileinfo variable

2 Likes

add a ToString after the item:
new Fileinfo(item.tostring)

i didn’t noticed that i changed the TypeArgument into string for the loop

2 Likes

Thanks theo500, in addition I needed to add a .ToString on the message box variable for this to run.

The output was the full “C:\users\documents\test1.xls” string again instead of just the file name.

Thanks for your continued help

3 Likes

Cool! In addition a training on datatypes would be helpful too.

3 Likes

in the message box you must put test.Name (instead of test.toString). This property returns only the file name

let me know if this worked

8 Likes

Thanks theo500, you are a legend. This worked perfectly.

3 Likes

When you have a full path, you can also use:
Path.GetFileName(fullPath) and Path.GetFileNameWithoutExtension(fullPath)
Both will return strings and you don’t need to create additional variables.

15 Likes

Hi theo500. I applied your method and it returns me only the last file name in alphabetic order.
Any chance to share XAML? or more explanation on what could be wrong in my selections? BR

1 Like

hope this will work fine for u

4 Likes

how to write the same list into a file with for each loop