22

How do I pull out the filename from a full path using regular expressions in C#?

Say I have the full path C:\CoolDirectory\CoolSubdirectory\CoolFile.txt.

How do I get out CoolFile.txt using the .NET flavor of regular expressions? I'm not really good with regular expressions, and my RegEx buddy and me couldn't figure this one out.

Also, in the course of trying to solve this problem, I realized that I can just use System.IO.Path.GetFileName, but the fact that I couldn't figure out the regular expression is just making me unhappy and it's going to bother me until I know what the answer is.

3
  • 17
    It's fine you want to know how it would work with regular expressions, but to make this world a better place, please promise that you'll use Path.* anyway :) Commented Oct 21, 2008 at 19:38
  • GetFileName may not be an option if you are working with Long Path Commented Jun 9, 2012 at 22:40
  • There are reasons for and against regex: codinghorror.com/blog/2008/06/… Commented Jul 9, 2012 at 0:29

6 Answers 6

40

Why must you use regular expressions? .NET has the built-in Path.GetFileName() method specifically for this which works across platforms and filesystems.

Sign up to request clarification or add additional context in comments.

3 Comments

You didn't read the question carefully. He's aware of GetFileName(), but wants to know how to do it with reg ex.
When I posted my answer that sentence was not there.
Then feel free to ignore me. :)
21
//  using System.Text.RegularExpressions;

/// <summary>
///  Regular expression built for C# on: Tue, Oct 21, 2008, 02:34:30 PM
///  Using Expresso Version: 3.0.2766, http://www.ultrapico.com
///  
///  A description of the regular expression:
///  
///  Any character that is NOT in this class: [\\], any number of repetitions
///  End of line or string
///  
///
/// </summary>
public static Regex regex = new Regex(
      @"[^\\]*$",
    RegexOptions.IgnoreCase
    | RegexOptions.CultureInvariant
    | RegexOptions.IgnorePatternWhitespace
    | RegexOptions.Compiled
    );

UPDATE: removed beginning slash

2 Comments

You realize that's going to get "\CoolFile.txt"
Good catch, didn't cross my mind that the slash wasn't supposed to be there when I tested it
7

Here's one approach:

string filename = Regex.Match(filename, @".*\\([^\\]+$)").Groups[1].Value;

Basically, it matches everything between the very last backslash and the end of the string. Of course, as you mentioned, using Path.GetFileName() is much easier and will handle lots of edge cases that are a pain to handle with regex.

1 Comment

+1 because I was able to solve a Perl regex issue with it. Thanks.
7

Shorter:

string filename = Regex.Match(fullpath, @"[^\\]*$").Value;

Or:

string filename = Regex.Match(fullpath, "[^\\"+System.IO.Path.PathSeparator+"]*$").Value;

Without Regex:

string[] pathparts = fullpath.Split(new []{System.IO.Path.PathSeparator});
string file = pathparts[pathparts.Length-1];

The official library support you mentioned:

string file = System.IO.Path.GetFileName(fullpath);

Comments

1
\w+:\\(\w+\\)*(?<file>\w*\.\w*)

This obviously would need expanding to cover all path characters, but the named group "file" contains your filename for the example path given.

2 Comments

just curious, what does next group do? (?<file>\w*\.\w*). should it be (?: )
@Artu: (?<file>\w*\.\w*) is a named capture group.
0

You should rather use the System.Path class. It will mean you will have to worry about less if you ever decide to support Mono/Linux (dlamblin's example takes the path seperator into account, but you may get a strange OS that has strange paths). The System.Path class can also combine two paths into one. So for example:

Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "My App Stuff");

would resolve to:

  • Windows: C:\Documents and Settings\[User]\My Documents\My App Stuff
  • Linux: /[User]/My App Stuff

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.