nav100
nav100

Reputation: 3153

How can I split a string to obtain a filename?

I am trying to split the string. Here is the string.

string fileName =   "description/ask_question_file_10.htm"

I have to remove "description/" and ".htm" from this string. So the result I am looking for "ask_question_file_10". I have to look for "/" and ".htm" I appreciate any help.

Upvotes: 5

Views: 7974

Answers (4)

Yahia
Yahia

Reputation: 70369

try

string myResult = fileName.SubString (fileName.IndexOf ("/") + 1);
if ( myResult.EndsWith (".htm" ) )
   myResult = myResult.SubString (0, myResult.Length - 4);

IF it is really a path then you can use

string myResult = Path.GetFileNameWithoutExtension(fileName);

EDIT - relevant links:

Upvotes: 2

sll
sll

Reputation: 62544

 string fileName = "description/ask_question_file_10.htm";
 string name = Path.GetFileNameWithoutExtension(fileName);

Upvotes: 1

Pawel Lesnikowski
Pawel Lesnikowski

Reputation: 6391

string fileName = Path.GetFileNameWithoutExtension("description/ask_question_file_10.htm")

Upvotes: 5

dtb
dtb

Reputation: 217401

You can use the Path.GetFileNameWithoutExtension Method:

string fileName = "description/ask_question_file_10.htm";

string result = Path.GetFileNameWithoutExtension(fileName);
// result == "ask_question_file_10"

Upvotes: 21

Related Questions