Use LastIndexOf(Char) to find the last directory separator character in a string and to extract the file name : String Search « String « C# / CSharp Tutorial






using System;
using System.IO;

public class MainClass
{
   public static void Main()
   {
      string filename;

      filename = ExtractFilename(@"C:\temp\notafile.txt");
      Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);
   }

   public static string ExtractFilename(string filepath)
   {
      if (filepath.Trim().EndsWith(@"\"))
         return String.Empty;

      int position = filepath.LastIndexOf('\\');
      if (position == -1)
      {
         if (File.Exists(Environment.CurrentDirectory + Path.DirectorySeparatorChar + filepath)) 
            return filepath;
         else
            return String.Empty;
      }
      else
      {
         if (File.Exists(filepath))
            return filepath.Substring(position + 1);
         else
            return String.Empty;
      }
   }
}








5.18.String Search
5.18.1.Search a character in a string
5.18.2.Search a character in a string: lastindex
5.18.3.Search a sub string in a string
5.18.4.Search a sub string in a string: lastIndexOf
5.18.5.Search any characters in a string
5.18.6.String starts with and ends with
5.18.7.Search a string from the start or from the end
5.18.8.Use LastIndexOf(Char) to find the last directory separator character in a string and to extract the file name
5.18.9.Find the index of the last occurrence of any character in the string "is" within another string.