Jason
Jason

Reputation: 259

How can I just get the base filename from this C# code?

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

Answers (4)

Evan Mulawski
Evan Mulawski

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

Pavel Metzenauer
Pavel Metzenauer

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

iamkrillin
iamkrillin

Reputation: 6876

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

Upvotes: 22

Oliver
Oliver

Reputation: 45111

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.

Upvotes: 1

Related Questions