To extract the filename from a file path in C#, you can use the Path
class from the System.IO
namespace. The Path
class provides various methods to manipulate file paths. The GetFileName
method is particularly useful for extracting the filename from a full file path. Here’s the C# code to do that:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = @"C:\path\to\your\file.txt";
string fileName = ExtractFileName(filePath);
Console.WriteLine($"Filename: {fileName}");
}
private static string ExtractFileName(string filePath)
{
try
{
// Get the filename from the file path.
string fileName = Path.GetFileName(filePath);
return fileName;
}
catch (Exception ex)
{
// Handle any exceptions that may occur during the extraction.
Console.WriteLine($"Error: {ex.Message}");
return null;
}
}
}
Replace C:\path\to\your\file.txt
with the actual file path from which you want to extract the filename. The code will use the Path.GetFileName
method to retrieve the filename from the file path and print it to the console.
Please note that the Path.GetFileName
method does not check whether the file actually exists on the disk; it simply extracts the filename from the provided path string. If the provided path is invalid or contains invalid characters, the method may return an unexpected result. Ensure that the path you pass to the ExtractFileName
method is valid and properly formatted.