Editing strings in C#

I am using Directory.GetFile() method to give me the list of all .txt files in my application path. Unfortunately it returns something like “C:/Document and setting/etc…/lol.txt”, the whole directory path with the file name and I cant display that on the listbox on my page. So, I thought I would make a For Loop that goes through each character in the string starting from right until it reaches “/” sign, then it removes the rest of the patch leaving only the file name.

I googled all “C# format string methods” and “edit strings C#” and “string methods C#” and came up with nothing useful. :confused:

I don’t really need the loop that does that, I only need the functions that will help me make the loop. Also, if theres an alternative to Directory.GetFile() method that returns only the file names would be more appreciated.

Thanks in advance.

look at the System.IO.Path class

System.IO.Path.GetFileName(path)

public IEnumerable<string> GetFiles(string path)
{
return Directory.GetFiles(path).Select(f => Path.GetFileName(f));
}

Thanks a lot pufa. :hangin:

1 More questions though :stuck_out_tongue:

Is theres some sort of a website which has Net library explained and sorted under categories…? I mean, it would have been impossible to discover GetFileName() method by myself if you didn’t introduce me to it, Moreover, to find methods in C# that formats/edits plain strings.

That would be MSDN Library

What IDE are you using? Visual Studio Intellisense (auto-completion) should list all members of a class… helps a lot in exploring APIs.

string.Format(“{0} {1}”, 0 ,1);
http://john-sheehan.com/blog/wp-content/uploads/msnet-formatting-strings.pdf

Thanks again Pufa.:cool:

And I am using visual C# express with Microsoft’s .net library :confused:

The namespaces are fairly well organised. Start from the MSDN class library (http://msdn.microsoft.com/en-au/library/ms229335.aspx) and just explore when the need arises.

For text formatting & manipulation, you would probably notice the System.Text namespace. Also, since what you’re formatting is a path, the System.IO namespace has a Path class.

Cheers,
D.

Now youre showing off :wink:

Yeah, you definitely can use the Path.GetFileName to get the name of the file, but if you want a string manipulation, then you can split your result with character “/” and then select the last part of the split. For example if the result you’re dealing with is added to a string variable pathFile, then you can do this

    string pathFile = "C:/documents/andre/smile.txt";
    string[] splitPathFile = pathFile.Split(new char[] { '/' });
    string fileName = splitPathFile[splitPathFile.Length - 1];

Hope this helps