Get File Name with Wildcard RRS feed

  • Question

  • I have a folder that will always only contain 1 file. The file name changes. How do I get the file name using a wildcard without looping through files in the directory since there's only 1 file?
    Sunday, January 20, 2019 3:46 PM


All replies

  • I think that you have to start enumerating the files:

    string path = @"C:\MyFiles";
    string filename = new DirectoryInfo( path ).EnumerateFiles().Single().Name;

    This fragment also ensures that the folder contains one and only one file.

    • Edited by Viorel_MVP Sunday, January 20, 2019 4:08 PM
    Sunday, January 20, 2019 4:07 PM
  • You could use regular expressions e.g.

    Regex reg = new Regex(@"^^(?!p_|t_).*");
    var files = Directory.GetFiles(yourPath, "*.png; *.jpg; *.gif")
                         .FirstOrDefault(path => reg.IsMatch(path));
    Adjust the pattern to match what you are looking for.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Sunday, January 20, 2019 4:26 PM
  • error on Single

    'IEnumerable<FileInfo>' does not contain a definition for 'Single' and no accessible extension method 'Single' accepting a first argument of type 'IEnumerable<FileInfo>' could be found (are you missing a using directive or an assembly reference?)

    • Edited by TinaFM Sunday, January 20, 2019 10:59 PM
    Sunday, January 20, 2019 8:48 PM
  • Probably you need 'using System.Linq;'.
    • Marked as answer by TinaFM Sunday, January 20, 2019 10:59 PM
    Sunday, January 20, 2019 9:09 PM