By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,259 Members | 1,709 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,259 IT Pros & Developers. It's quick & easy.

Return folder name from file location path

P: 6
How would I retrive the folder name a file is in?
In this example I just want the highlighted folder name:

C:\Program Files\FolderNameIWant\Application.exe

I can get the path excluding the file using various methods such as:

Expand|Select|Wrap|Line Numbers
  1. Dim intPos As Integer
  2. intPos = FileFullPath.LastIndexOfAny("\")
  3. intPos += 1
  4., intPos))
But cannot figure out how to return just the top level folder!

Jun 4 '10 #1
Share this Question
Share on Google+
6 Replies

Expert 2.5K+
P: 3,525
Use string.split to separate on the '\' character
The folder name will be the last element of the returned array.

There are a number of methods in the System.IO.Path namespace that might make things easier on you as well.
There are existing methods for GetFileName, RootPath, GetFileNameWithoutExtension and so on
Jun 4 '10 #2

P: 6
I tried using Split but it seems to return the string in it's original format?

strCustomerName.Split(New Char() {"\"c})

I could not find anything in the System.Io.Path that would be of any use.
Jun 4 '10 #3

Expert 2.5K+
P: 3,525
Then you didn't bother to read about how string.split works.

Here is some general good advice. Don't just assume you know how a function will work based on its name and your guesswork. You could spend a lot of time dinking around with it, tons of trial and error and eventually figure out what it does. Or you could just go to the MSDN and read about and look at the explanation and samples.

String.split does not affect or alter your original string. It is a method that returns an array of strings.

string[] Yogi = string.split("c:\one\two\three", '\');

Will assign elements to the new array[] Yogi as follows
[0] = c:
[1] = one
[2] = two
[3] = three

So if you take your total GetPathWithoutFileName
.split() it on the '\'
the last element will be the folder name.
Jun 4 '10 #4

P: 6
Directory.Name does the job:

Expand|Select|Wrap|Line Numbers
  1. Dim filepath As String = "C:\Program Files\FolderNameIWant\cats\Application.exe"
  2.             Dim fi As New IO.FileInfo(filepath)
  3.             MessageBox.Show(fi.Directory.Name)
Thanks for your advice.
Jun 4 '10 #5

P: 1
Expand|Select|Wrap|Line Numbers
  1. 1.Dim filepath As String = "C:\Program Files\FolderNameIWant\cats\Application.exe"
  2. 2.             Dim fi As New IO.FileInfo(filepath)
  3. 3.             MessageBox.Show(fi.Name)
  4. returns the Folder
Apr 15 '14 #6

P: 6
Name = Name.Substring(InStrRev(Name, "\"))
Oct 9 '14 #7

Post your reply

Sign in to post your reply or Sign up for a free account.