Split string in vb.net

RIAS
RIAS used Ask the Experts™
on
Hi,
I have a string
str1 = "z:\str1\str2\str3"
The query is how to get
str2=  "z:\str1\str2"
eliminate last \str3

Cheers
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Assuming this is a file path:

str2 = New FileInfo(str1).Directory.FullName

Open in new window

Paul JacksonSoftware Engineer
Top Expert 2011

Commented:
Dim str1 as String = "z:\str1\str2\str3"
Dim pos as Integer = str1.LastIndexOf("\")
Dim str2 as String = str1.SubString(0, (pos -1))
You could do something like this. Instead of just outputting the string to the console put the portions you want into an array and build your new path.

http://www.dotnetperls.com/split-vbnet

Split parts of file path
Here we see how you can Split a file system path into separate parts using Visual Basic .NET. We use a New Char() array with one string, "\""c, and then loop through and display the results.

Program that splits file path [VB.NET]

Module Module1

    Sub Main()
      ' The file system path we need to split
      Dim s As String = "C:\Users\Sam\Documents\Perls\Main"

      ' Split the string on the backslash character
      Dim parts As String() = s.Split(New Char() {"\"c})

      ' Loop through result strings with For Each
      Dim part As String
      For Each part In parts
          Console.WriteLine(part)
      Next
    End Sub

End Module

Output

C:
Users
Sam
Documents
Perls
Main
Commented:
If you are looking for a "hard coded" string manipulation solution, then try
Dim str1 as String = "z:\str1\str2\str3"
Dim Result = str1.Replace("\" & str1.Split("\").Last, String.Empty)

Open in new window

Here's some more that use Regex & whitespace to split
http://www.dotnetperls.com/regex-split-vbnet

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial