Reputation: 9496
How to find a specific file in a specific directory with LINQ and return true if it exists?
Upvotes: 0
Views: 4938
Reputation: 3385
You can also consider FluentPath if you like such a thing. It is a Fluent wrapper around System.IO I saw a while back. Here is a sample from the site:
Path.Get(args.Length != 0 ? args[0] : ".")
.Files(
p => new[] {
".avi", ".m4v", ".wmv",
".mp4", ".dvr-ms", ".mpg", ".mkv"
}.Contains(p.Extension))
.CreateDirectories(
p => p.Parent()
.Combine(p.FileNameWithoutExtension))
.End()
.Move(
p => p.Parent()
.Combine(p.FileNameWithoutExtension)
.Combine(p.FileName));
Upvotes: 1
Reputation: 3848
var doesExist = new DirectoryInfo(folder).GetFiles(fileName, SearchOption.AllDirectories).Any();
Upvotes: 3
Reputation: 3431
You can do it like this:
var fileExists = new DirectoryInfo("directoryPath").GetFiles("filename.ext").Any();
But you could just use this if you already know the path of the file:
var fileExists = File.Exists("filePath");
Upvotes: 4
Reputation: 40160
Why would you use LINQ for this? This does what you need:
string filePath = Path.Combine(directory, fileName);
return File.Exists(filePath);
Upvotes: 11