Regular Expression: how to get Filename from Path

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I tried to use to code to get a file name from a file path but it's working
in all case.

string t12 = "\"C:\\Program Files\\Microsoft SQL
Server\\MSSQL.1\\MSSQL\\Binn\\sqlservr.exe";
string p12 = @"^.*\\";
string r12 = Regex.Replace(t12, p12, "");

I got a correct answer for this case, which is sqlservr.exe
but when my path name changed to

string t12 = "\"C:\\Program Files\\Microsoft SQL
Server\\MSSQL.1\\MSSQL\\Binn\\sqlservr.exe\" -sSQLEXPRESS";

I received a wrong answer: sqlservr.exe" -sSQLEXPRESS

Any idea?
 
Hello!
Did you try Path.GetFileName ?

Yeah, this is what I'd have asked, too. Regular expressions sounds like the
wrong tool for this.

Ano, try this code instead:

string t12 = "\"C:\\Program Files\\Microsoft SQL " +
"Server\\MSSQL.1\\MSSQL\\Binn\\sqlservr.exe\" -sSQLEXPRESS";
string[] parts = t12.Split('\"');
string filename = System.IO.Path.GetFileName(parts[1]);
MessageBox.Show(filename);

--
Regards,

Mr. Jani Järvinen
C# MVP
Helsinki, Finland
(e-mail address removed)
http://www.saunalahti.fi/janij/
 
System.IO.Path.GetFileName(string path)

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Chicken Salad Alchemist

Big thicks are made up of lots of little thins.
 
ano said:
Hi,

I tried to use to code to get a file name from a file path but it's
working in all case.

string t12 = "\"C:\\Program Files\\Microsoft SQL
Server\\MSSQL.1\\MSSQL\\Binn\\sqlservr.exe";
string p12 = @"^.*\\";
string r12 = Regex.Replace(t12, p12, "");

I got a correct answer for this case, which is sqlservr.exe
but when my path name changed to

string t12 = "\"C:\\Program Files\\Microsoft SQL
Server\\MSSQL.1\\MSSQL\\Binn\\sqlservr.exe\" -sSQLEXPRESS";

I received a wrong answer: sqlservr.exe" -sSQLEXPRESS

Well, your second example is not a path - it's a command line, including
arguments. First you have to remove the arguments. There's no standard way
to do that, but generally it'll be everything after the first whitespace, or
if the path portion begins with a quotation mark, then everything after the
second quotation mark.

Once you've separated the path from the arguments, use System.IO.Path to
split out the parts of the path, as others have suggested.

-cd
 
Back
Top