get the name of a file from the path in csharp

To get the name of a file from the path in c#, you can use the Path.GetFileName method. This method takes a string parameter which is the path of the file and returns the name of the file as a string.

Here is an example code snippet that demonstrates how to use the Path.GetFileName method:

main.cs
string filePath = "C:/Users/username/Desktop/example.txt";
string fileName = Path.GetFileName(filePath);
Console.WriteLine("File name: " + fileName); // Output: File name: example.txt
184 chars
4 lines

In the above example, we first define a string variable filePath that holds the path of a file. We then pass this variable as a parameter to the Path.GetFileName method and store the returned value in another string variable fileName. Finally, we print the fileName variable to the console.

Note that the Path.GetFileName method works with both forward slashes (/) and backslashes (\) as path separators.

related categories

gistlibby LogSnag