hi,

i am basically adding files to my listview through this code

For each n as string in my.computer.filesystem.getdirectories("C:\Testing\")
Listview1.items.add(n,Imagelist1.images.count - 1)
Next

so all the files inside testing folder show up on the listview
the problem is that they all show up but they show up with the path such as instead of showing test.txt, they would show C:\Testing\test.txt
can anyone please tell me how to only show the filename and not the whole path

any help will be appreciated

Dani AI

Generated

Good catch by — the reason your first attempt didn’t change what appears in the ListView is that string methods like Replace return a new string; you must use that returned value (which is what you did when assigning to NewString). For a cleaner, more reliable solution use the framework helper that extracts a filename from any path instead of doing manual string replaces.

A compact, robust pattern is to enumerate the files and call System.IO.Path.GetFileName for each item:

For Each path As String In My.Computer.FileSystem.GetFiles("C:\Testing")
    Dim name As String = System.IO.Path.GetFileName(path)
    ListView1.Items.Add(name, ImageList1.Images.Count - 1)
Next

Notes and quick troubleshooting:

  • If you actually want directories instead of files, use GetDirectories; GetFiles returns files. See My.Computer.FileSystem.GetFiles and Path.GetFileName for details.
  • Path.GetFileName handles edge cases (trailing slashes, different roots) better than manual replace.
  • Check ImageList1.Images.Count before using Images.Count - 1 to avoid negative indexes.
  • For large folders, wrap updates in ListView.BeginUpdate / EndUpdate to avoid flicker and improve speed.
  • If you want the name without extension use Path.GetFileNameWithoutExtension.

This approach is more maintainable than hardcoded replaces and will keep the ListView display correct even if the source path format changes.

Recommended Answers

All 5 Replies

Hi
This is VB.NET code, I think so.
Try

For each n as string in my.computer.filesystem.getdirectories("C:\Testing\")
n.Replace ( "C:\Testing\", "" )
Listview1.items.add(n,Imagelist1.images.count - 1)
Next

I Dont know whether it is right or wrong. Please try it

No, it wont work it would still show the whole address

if this thread for .net please post in vb.net section.

No, it wont work it would still show the whole address

Try This

Dim NewString as String 

For each n as string in my.computer.filesystem.getdirectories("C:\Testing\")
   NewString = n.Replace ( "C:\Testing\", "" )
   Listview1.items.add(NewString,Imagelist1.images.count - 1)
Next

I Think Strings are Immutable

Thanks a lot, selvaganapathy, it worked.

I really appreciate it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.