16

I have the following code:

string[] files = Directory.GetFiles(@"C:\Notes", "*.txt", SearchOption.TopDirectoryOnly);
foreach(string file in files)

When I check the contents of file it has the directory path and extension. Is there a way I can just get the filename out of that?

Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
Jason
  • 239
  • 1
  • 2
  • 5
  • 2
    As an aside.. You probably shouldn't be calling these things file and files. Those things generally refer to file descriptors on unix and file handles(??) on windows. It would probably be (slightly) clearer to people perusing your code to call them filename and filenames respectively. – demented hedgehog Oct 06 '15 at 08:56

4 Answers4

41

You can use the FileInfo class:

FileInfo fi = new FileInfo(file);
string name = fi.Name;

If you want just the file name - quick and simple - use Path:

string name = Path.GetFileName(file);
Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
  • 5
    Becuase this is so overkill. My tests indicate that it is approximately 11 times slower than just `Path.GetFileName`. There are correct times to use both, but this is not the time to use `FileInfo` – Oskar Kjellin Aug 09 '11 at 13:54
  • Check this question as well http://stackoverflow.com/questions/4979762/new-fileinfopath-name-versus-path-getfilenamepath – Oskar Kjellin Aug 09 '11 at 13:55
  • 4
    @Oskar: The OP never indicated performance requirements. Also, no one is sure what other information the OP will need for his application, like file attributes. – Evan Mulawski Aug 09 '11 at 13:57
  • @Evan does that really matter? I don't think this is a good way to do it, thus the downvote – Oskar Kjellin Aug 09 '11 at 13:57
  • 1
    @Evan if he needs the fileinfo class in a foreach loop, it is faster to create a DirectoryInfo and use GetFiles if I recall correctly – Oskar Kjellin Aug 09 '11 at 14:07
20

You can use the following method: Path.GetFileName(file)

Brian Dishaw
  • 5,767
  • 34
  • 49
iamkrillin
  • 6,798
  • 1
  • 24
  • 51
4
System.IO.FileInfo f = new System.IO.FileInfo(@"C:\pagefile.sys");  // Sample file.
System.Windows.Forms.MessageBox.Show(f.FullName);  // With extension.
System.Windows.Forms.MessageBox.Show(System.IO.Path.GetFileNameWithoutExtension(f.FullName));  // What you wants.
  • 2
    Firstly, `FileInfo.FullName` will give you the *full* filepath which is not what the question asks. Secondly, if you are going to use `System.IO.Path` methods, why bother creating a `FileInfo` object in the first place? – Peter Monks Mar 22 '12 at 15:26
1

If you need to strip away the extension, path, etc. you should fill this string into a FileInfo and use its properties or use the static methods of the Path class.

Oliver
  • 43,366
  • 8
  • 94
  • 151