Willem
Willem

Reputation: 9496

LINQ to Files/Directory

How to find a specific file in a specific directory with LINQ and return true if it exists?

Upvotes: 0

Views: 4938

Answers (4)

Jaapjan
Jaapjan

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

Howard
Howard

Reputation: 3848

var doesExist = new DirectoryInfo(folder).GetFiles(fileName, SearchOption.AllDirectories).Any();

Upvotes: 3

Simon Stender Boisen
Simon Stender Boisen

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

Andrew Barber
Andrew Barber

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

Related Questions