# using string to trim filename from path

This topic is 3317 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I am new to C# and I have never used the String class much. I have a complete path in a String String myPath = "C:\\directory\\subdirectory\\file.dat"; what can i do with myPath to get it to hold the data... "C:\\direcotory\\subdirectory\\" Thanks for your help, I have googled this and all I find is a buch of VB stuff.

##### Share on other sites
Quote:
 Original post by SelethDI am new to C# and I have never used the String class much. I have a complete path in a StringString myPath = "C:\\directory\\subdirectory\\file.dat";what can i do with myPath to get it to hold the data..."C:\\direcotory\\subdirectory\\"Thanks for your help, I have googled this and all I find is a buch of VB stuff.

Check out System.IO.Path. I believe the method is GetDirectoryName.

##### Share on other sites
I tried system.io.path, and its not working for me.

I need simply to know how to remove the text from a String after the last occuring '/'

##### Share on other sites
How is it not working? What have you tried, what did it do and what did you expect it to do instead? System.IO.Path is definitely what you want.

##### Share on other sites
Quote:
 Original post by SelethDI tried system.io.path, and its not working for me.I need simply to know how to remove the text from a String after the last occuring '/'

What do you mean "its not working" for you? Please post the relevant code.

I suppose you could do it with String.LastInstanceOf and String.SubString.

##### Share on other sites
How it didnt work for me, is that system.io.path is a 'type'

So how does that help me? I dont quite understand it. (Thus the reason im posting in beginners)

##### Share on other sites
Quote:
 Original post by SelethDHow it didnt work for me, is that system.io.path is a 'type'

OK, you want to use the GetDirectoryName method of the Path class, like so:

string myPath = "C:\\directory\\subdirectory\\file.dat";string directoryName = Path.GetDirectoryName(myPath);

##### Share on other sites
if you're dead set on parsing it manually(although the above idea is better), just check each char of the string starting at the end, something like this. this is partial psudo code because I'm not familiar with C#'s string object.

string path = "C:\\mydir\\myfile.txt";
int pathStart = -1;
//if pathStart == -1, there is no path, or there are is no hierarchy of directories
//assumes char at position can be acessed using [], and that it's zero-indexed

for(int i = path.length();i>0;--i)
{
if(path == '\')
{
if(path[i - 1] == '\')
{

pathStart = i+ 1;
//do a check to see if pathStart is within string size, too lazy
break;
}
}
}