How to get the string before period

  • Thread starter Thread starter ad
  • Start date Start date
A

ad

I want to get the string before period.
For example a string: "Home.aspx", I want to get the "Home"
How can I do that with C#?
 
ad said:
I want to get the string before period.
For example a string: "Home.aspx", I want to get the "Home"
How can I do that with C#?

Use String.IndexOf to find the first dot, and then String.Substring to
get the part before the dot.
 
try:

string strFile = "Home.aspx";

string strNameWithoutExtension = strFile.Split(new char[]{'.'})[0];

Mark.
 
A nice clean way to do this is to use the System.IO.Path class:

string fileName = "home.aspx";
string baseName =
Path.GetFileNameWithoutExtension(fileName);


The Path class has a number of static methods that parses path names,
such as:

GetFullPath() : Gets the absolute path
GetPathRoot() : Gets the root directory info
GetDirectionName(): Get the directory info for a path
etc...

Bennie Haelen
try:

string strFile = "Home.aspx";

string strNameWithoutExtension = strFile.Split(new char[]{'.'})[0];

Mark.

:

I want to get the string before period.
For example a string: "Home.aspx", I want to get the "Home"
How can I do that with C#?
 
ad said:
I want to get the string before period.
For example a string: "Home.aspx", I want to get the "Home"
How can I do that with C#?

Be careful: if you're trying to remove the file extension, then Bennie's
solution is the only correct one listed here. You have to consider filenames
such as "Stuff.stuff.asp" and "Stuff" which have more or less than one
period.
 
Back
Top