find the name of a file in csharp

To find the name of a file in C#, you can use the System.IO namespace, and pass the file path as a string to the Path.GetFileName() method. Here is an example code snippet:

main.cs
using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        // File path
        string filePath = @"C:\Users\username\Documents\example.txt";

        try
        {
            // Get the file name
            string fileName = Path.GetFileName(filePath);

            Console.WriteLine("File name: " + fileName);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
        }
    }
}
473 chars
24 lines

In this code, we are using the Path.GetFileName() method to get the file name from the filePath string. We have also wrapped the code in a try-catch block to handle any exceptions that may occur while accessing the file.

gistlibby LogSnag