Reputation: 259
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?
Upvotes: 18
Views: 30205
Reputation: 55334
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);
Upvotes: 44
Reputation: 41
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.
Upvotes: 4