LINQ to Files/Directory
How to开发者_StackOverflow中文版 find a specific file in a specific directory with LINQ and return true if it exists?
Why would you use LINQ for this? This does what you need:
string filePath = Path.Combine(directory, fileName);
return File.Exists(filePath);
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");
var doesExist = new DirectoryInfo(folder).GetFiles(fileName, SearchOption.AllDirectories).Any();
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));
精彩评论