Trim Drive Letter From Listbox

February 15, 2011 at 19:29:35
Specs: Windows XP
I am putting a list of files into a listbox from a directory and its subdirectories. Is there a way to remove the drive letter for each file but keep the other file information. For example:
Original Entry = C:\Test\Folder\testfile1
How it shows up in the listbox = Test\Folder\testfile1

Here is my code so far:


Imports System.IO

Public Class Form1
Private Sub btnStart_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnStart.Click

Dim CopyFiles As List(Of String) = GetData(SourcePath)

' Loop through and display each path.
Dim file As String
For Each file In CopyFiles
FileListBox.Items.Add(file)
Next

' Write total number of paths found.
TotalBox.Text = (CopyFiles.Count)
End Sub


Public Shared Function GetData(ByVal initial As String) As List(Of String)
' This list stores the results.
Dim result As New List(Of String)

' This stack stores the directories to process.
Dim stack As New Stack(Of String)

' Add the initial directory
stack.Push(initial)

' Continue processing for each stacked directory
Do While (stack.Count > 0)
' Get top directory string
Dim dir As String = stack.Pop
Try
' Add all immediate file paths
result.AddRange(Directory.GetFiles(dir, "*.*"))

' Loop through all subdirectories and add them to the stack.
Dim directoryName As String
For Each directoryName In Directory.GetDirectories(dir)
stack.Push(directoryName)
Next

Catch ex As Exception
End Try
Loop

' Return the list
Return result
End Function


End Class


See More: Trim Drive Letter From Listbox

Report •


#1
February 15, 2011 at 23:12:02
Without actually looking at your code:
Test if the second character is ":". If it is, strip out the first three characters.

How To Ask Questions The Smart Way


Report •

#2
February 16, 2011 at 10:45:47
Hello Razor2.3

I posted my code that I am using. I would like to strip out the first characters but I do not know how.


Report •

#3
February 18, 2011 at 06:23:09
Fine. I'll be nice and write the whole 7 lines of code.
  Private Sub btnStart_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnStart.Click
    Dim CopyFiles As List(Of String) = GetData(SourcePath.Text)
    Dim stripDrive = Function(s As String)
                       If s(1) = ":" Then
                         Return s.Substring(3)
                       End If
                       Return s
                     End Function

    ' Loop through and display each path.
    Dim file As String
    For Each file In CopyFiles
      FileListBox.Items.Add(stripDrive(file))
    Next

    ' Write total number of paths found.
    TotalBox.Text = (CopyFiles.Count)
  End Sub

How To Ask Questions The Smart Way


Report •

Related Solutions


Ask Question