Extract file name from path

  • Thread starter Kristoffer Persson
  • Start date
K

Kristoffer Persson

It's probably very simple... I would like to know if there is a function
similar to ExtractFileName() (I've used it in Delphi), which returns only
the file name from the full path, e.g. "C:\Temp\MyFile.txt" would return
"MyFile.txt".

Thanks!

- Kristoffer -
 
V

Vladimir Scherbina

hm, I found no function that performs this. so I suppose this will help
you...

string GetFileName(string szPath)

{

string szRetVal = string.Empty;

string szTmp = string.Empty;

int j = szPath.Length - 1;

while (szPath[j] != '\\')

{

szTmp += szPath[j];

j--;

}


// you have the reversed file name

// replace characters...


int i = szTmp.Length;

while (i != 0)

{

i--;

szRetVal += szTmp;

}

szTmp = null;

return szRetVal;

}
 
L

L#

It's probably very simple... I would like to know if there is a function
similar to ExtractFileName() (I've used it in Delphi), which returns only
the file name from the full path, e.g. "C:\Temp\MyFile.txt" would return
"MyFile.txt".

Thanks!

- Kristoffer -

System.IO.Path.GetFileName(string path);
 
R

Roman S. Golubin

Hi, Vladimir Scherbina!
hm, I found no function that performs this. so I suppose this will help
you...

string GetFileName(string szPath)

{

string szRetVal = string.Empty;

string szTmp = string.Empty;

int j = szPath.Length - 1;

while (szPath[j] != '\\')

{

I optimize your code ;-)

string GetFileName(string szPath)
{
string[] s_arr = szPath.Split(new char[]{'\\'});
return s_arr[s_arr.Length-1];
}

or

string GetFileName(string szPath)
{
Regex r = new Regex(@"\w+[.]\w+$+");
return r.Match(szPath).Value;
}
 
R

Roman S. Golubin

Hi, Kristoffer Persson!
It's probably very simple... I would like to know if there is a function
similar to ExtractFileName() (I've used it in Delphi), which returns only
the file name from the full path, e.g. "C:\Temp\MyFile.txt" would return
"MyFile.txt".

string ExtractFileName(string szPath)
{
Regex r = new Regex(@"\w+[.]\w+$+");
return r.Match(szPath).Value;
}
 
R

Robert Sentgerath

The static methods of Path give you a myriad of options to deal with file
names that include the path.

For example:

string myFile = "C:\Temp\MyFile.txt";
string filename = Path.GetFileName(myFile);

You could also get the name without extension:

filename = Path.GetFileNameWithoutExtension(myFile);

Just browse through all the different methods that Path gives you to see
what else you can do.

- Robert Sentgerath -


Path.GetFileNameWithoutExtension
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top