Search code examples
c#directoryfilenamesfile-exists

Check existing file and return the name of file


I have a folder: E:\Photo. I want to check is there any file ".CR2" in the folder. If it exists, return the name of file ".CR2" (For ex, return E:\Photo\0102.CR2). I just know how to check whether existing file ".CR2" by File.Exist(), but I don't know how to return the file name. How can I do that in C#?


Solution

  • DirectoryInfo.GetFiles is what you´re looking for:

    var files = Directory.GetFiles(@"E:\Photo\*.CR2");
    

    This will get all files with the extension CR2. If you need just the first use files.First().