Prabhagaran P
Prabhagaran P

Reputation: 105

How to Filter file from directory by using File name using linq?

var GetFileByFileName = Directory.GetFiles(SourceFilePath)
                                       .Select(x => new FileInfo(x))
                                       .Where(x => x.Name==SourceFileName)
                                       .Take(1)
                                       .ToArray();

This is my code for fetch file by Specified File name.Here i am using array . In here SOURCEFILENAME is an string variable which having the file name.but it is not working.i could get all files from directory.but i need only one file from directory based on the SOURCEFILENAME.? Please help me..Thank You. .

Upvotes: 3

Views: 4157

Answers (3)

Dhaval Patel
Dhaval Patel

Reputation: 7601

if you want to use the way what you currently used then you have implement be in below mentioned way

 var GetFileByFileName = Directory.GetFiles(@"D:\Re\reactdemo")
                                       .Select(x => new FileInfo(x))
                                       .Where(x => x.Name == "package.json")
                                       .Take(1)
                                       .ToArray();

check your SourcePath should look like what I have hard coded in code and your source file should be with extension

Upvotes: 4

loopedcode
loopedcode

Reputation: 4893

Why do you need to search among all files using linq, when you have both filename and the path? Your linq query is comparing == SourceFileName which is what you will get by directly seeking file using standard File operation.

var file = Path.Combine(SourceFilePath, SourceFileName);

//check if exists
if (File.Exists(file))
{
  // open your file to read it as needed
  // e.g. reading as text:
  var content = File.ReadAllText(file);

}

Upvotes: 0

Arghya C
Arghya C

Reputation: 10078

Your code is fine, and should work.

Alternatively, you can do it without Linq. Directory.GetFiles has an overload that accepts the file search pattern, where you can pass your file name.

var fileInfo = Directory.GetFiles(SourceFilePath, SourceFileName);

Where, for example

var SourceFilePath = @"C:\MyBackUp\Files";
var SourceFileName = @"MyTextFile.txt";

See this for reference.

Upvotes: 0

Related Questions