Question

I Get list of files listed in a folder called Book like this

string[] files = Directory.GetFiles("Book");

and I put these files name as button texts in my app . buttons texts get like this :

Book\1.mp3
book\2.mp3

I want to remove this Book\ from texts. How can I do that?

Était-ce utile?

La solution 3

If you want to get to the names:

string[] files = new DirectoryInfo("Book").GetFiles().Select(f => f.Name).ToArray();

I don't know how much overhead getting the directoryinfo really would introduce. But if it seems overkill as suggested you can use Path.GetFileName.

Autres conseils

If you just want the filename then you can use Path.GetFileName

You can use Path.GetFileName to get the file name from the path. Here is the example

string filename = Path.GetFileName(@"Book\1.mp3");

here in filename you will get 1.mp3

Assuming the directory is always called "Book":

string[] files = Directory.GetFiles("Book").Select(f => f.Substring(5));

This will strip out the beginning of the text ("Book\") leaving you with just the file name itself.

As you got the names from Directory.GetFiles so the return list is obviously file paths. You can separate the file name from a path or relative path using following api

string name = Path.GetFileName(@"\Book\test.mp3");

it will give you test.mp3 in return. See detail about Path.GetFileName

using Replace funciton

 files[0].Replace("Book\","");
    files[1].Replace("Book\","");

Use for loop 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top