Searching for a file in all directories - c#

I need to find the file and also return the address of the file. I already tried, but it does not work.
Do you have any idea how to do this?
I was using this code:
var files = new List<string>();
//#Stan R. suggested an improvement to handle floppy drives...
//foreach (DriveInfo d in DriveInfo.GetDrives())
foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady == true))
{
files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, actualFile, SearchOption.AllDirectories));
}

I just created a quick test and Directory.GetFiles does return the entire path (what you're calling address) to the file. The Microsoft documentation (https://msdn.microsoft.com/en-us/library/07wt70x2(v=vs.110).aspx) says it returns:
An array of the full names (including paths) for the files in the specified directory, or an empty array if no files are found.
If you still need the complete FileInfo, you could do something like this... (There are more elegant ways, but this will get you want you want.)
var files = new List<string>();
foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady == true))
{
var matchingFiles = Directory.GetFiles(d.RootDirectory.FullName, actualFile, SearchOption.AllDirectories));
foreach (var matchedFile in matchingFiles)
{
var fileInfo = new FileInfo(matchedFile);
// The newly created fileInfo will have everything you need, including path inside the FullName
files.Add(fileInfo.FullName);
}
}
I hope this helps.

Related

How to get the full path from a segment of a path and the filename in c#

Suppose I forget the full path of a file on my computer, but I remember the filename and a segment of the path.
example:
my filename is test and the segment of the path that I sill remember is \test1\test2
So I would like to get the full path with c#, like this: C:\test1\test2\test3\test4\test.txt
Thanks in advance!
If the segment you know is at the start of the path, you can do something like
DirectoryInfo f = new DirectoryInfo(#"C:\test1\test2");
var results = f.GetFiles("test.txt", SearchOption.AllDirectories);
If not, I'm afraid that you have to do a full search on the computer, and check if the result path contains your fragment.
You can go through all the files on the drive and check whether they match what you want: (This will be slow and resource consuming.)
var files = Directory.GetFiles(#"C:\", "test.txt", SearchOption.AllDirectories)
.Where(s => s.Contains(#"\test1\test2\"));
foreach (var f in files)
{
Console.WriteLine(f);
}
Or you know the root directory in which you want to search, you can change it like this to be faster:
var files = Directory.GetFiles(#"C:\test1\test2", "test.txt", SearchOption.AllDirectories);
foreach (var f in files)
{
Console.WriteLine(f);
}

c# how to get files name into a specific folder which have a specific pattern

I have a folder that contains these files:
Erb3PCustsExport-303_20080318_223505_000.xml
Erb3PCustsExport-303_20080319_063109_000_Empty.xml
Erb3PCustsImport-303_20080319_123456.xml
Erb3PDelCustsExport-303_20080319_062410_000.xml
Erb3PResosExport-303_20080318_223505_000_Empty.xml
Erb3PResosExport-303_20080319_062409_000.xml
I just care about the files that have CustsExport word in their names.
My question:
How to get these files?
What I have tried:
I got the folder name from app settings section in App.Config like this:
string folderPath = ConfigurationManager.AppSettings["xmlFolder"];
Then I got all the file names like this:
foreach (string file in Directory.EnumerateFiles(folderPath, "*.xml"))
{
}
My problem:
In that way, I got all the files. However, I am just interested in files that have CustsExport in their names.
Could you help me please?
Note:
I am working on .NET 4.5
Try this:
foreach (string file in Directory.EnumerateFiles(folderPath, "*CustsExport*.xml"))
{
}
Or your can use regex:
Regex reg = new Regex(#".*CustsExport.*\.xml",RegexOptions.IgnoreCase);
var files = Directory.GetFiles(yourPath, "*.xml")
.Where(path => reg.IsMatch(path))
.ToList();
You can use string.Contains("")
string folderPath = ConfigurationManager.AppSettings["xmlFolder"];
foreach (string file in Directory.EnumerateFiles(folderPath, "*.xml"))
{
if (file.Contains("CustsExport"))
{
//add your code
}
}

How to delete back up files

I need to delete files with ".bak" and ".csv.bak" extensions. I use .net c#.
I tried like this:
string srcDir = #"D:\Backup";
string[] bakList = Directory.GetFiles(srcDir,".bak");
if (Directory.Exists(srcDir))
{
foreach (string f in bakList)
{
File.Delete(f);
}
}
But when debugging, the bakList array is empty.
Directory.GetFiles() is not loading the file names in the array. I cant figure out what is wrong in my coding.
You need to Add * before your .bak in GetFiles()
string srcDir = #"D:\Backup";
string[] bakList = Directory.GetFiles(srcDir,"*.bak");
if (Directory.Exists(srcDir))
{
foreach (string f in bakList)
{
File.Delete(f);
}
}
If you need to search for both types maybe it works better
var files = Directory.GetFiles(srcDir, "*.*")
.Where(s => s.EndsWith(".bak"));
If your file name is
"Data Logger[2].csv.bak",
go to the properties and check the type of file. it will be something like this
"1 File (.1)" .The file has number as its end extension. So i used like this.
string[] bk = Directory.GetFiles(srcDir, "*.bak.*");
foreach (string f in bk)
{
File.Delete(f);
}
its working...

Find the difference of two folders and delete files

I have two folders : FolderA and FolderB
I want to delete the files in FolderA which also exist in FolderB. (i.e. Common files will be deleted from folderA)
How can I do this most efficiently in C#? (That's a critical point in the project and it has to be as efficient as possible )
Thanx
This is easy, readable and also efficient:
var common = from f1 in Directory.EnumerateFiles(folderA, "*.*", SearchOption.AllDirectories)
join f2 in Directory.EnumerateFiles(folderB, "*.*", SearchOption.AllDirectories)
on Path.GetFileName(f1) equals Path.GetFileName(f2)
select f1;
foreach (string file in common)
{
File.Delete(file);
}
Assuming that you just want to compare the file names (and extension).
You can do this with the help of LINQ. See here.
If you only want to compare file names, here is how you can do it, I did a quick test of this code and it works:
string pathA = #"C:\New FolderA";
string pathB = #"C:\New FolderB";
var filesA = Directory.GetFiles(pathA).Select(path => Path.GetFileName(path));
var filesB = Directory.GetFiles(pathB).Select(path => Path.GetFileName(path));
var toBeDeleted = filesA.Intersect(filesB);
foreach (string filename in toBeDeleted)
File.Delete(Path.Combine(pathA, filename));
string[] FolderAFiles = Directory.GetFiles(#"Path");
string[] FolderBFiles = Directory.GetFiles(#"BPath");
foreach (string Files in FolderAFiles)
{
if (FolderBFiles.Contains(Files))
{
File.Delete(Files);
}
}
Try this
Here's one another solution.
var filesInB = System.IO.Directory.GetFiles("FolderB");
Array.ForEach(System.IO.Directory.GetFiles("FolderA"), delegate(string fileName){
if (filesInB.Contains(fileName)) System.IO.File.Delete(fileName);
});

How to check for file names in a folder

I would like to be able to iterate through the name of some image files in a folder using c#. So for intance I have a folder named image and contains the following images
image
dog.jpg
cat.jpg
horse.jpg
I want to be able to go through the names and be able to say
if(filename == dog.jpg)
return true
else
return false
Something of that nature
Thank you
You should use the static Exists method on System.IO.File.
return System.IO.File.Exists("dog.jpg")
Since the method returns a boolean, there is no need for the if statement in the example you gave.
You can also use a bit of Linq magic to determine if a file exists in a folder structure, like this:
var dir = new System.IO.DirectoryInfo(startFolder);
var fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
bool fileExists = fileList.Any(f => f.FullName == "dog.jpg");
or even shorter:
return System.IO.Directory
.GetFiles(#"c:\myfolder", "dog.jpg", SearchOption.AllDirectories)
.Any();
which would search the folder specified and all subfolder with the pattern "dog.jpg". The Any() extension method simply checks whether the IEnumerable contains any items. I think this is the most efficient way of doing this (based on gut feeling).
From http://weblogs.asp.net/israelio/archive/2004/06/23/162913.aspx Just insert your if in the "// do something with filename" area:
// How much deep to scan. (of course you can also pass it to the method)
const int HowDeepToScan=4;
public static void ProcessDir(string sourceDir, int recursionLvl)
{
if (recursionLvl<=HowDeepToScan)
{
// Process the list of files found in the directory.
string [] fileEntries = Directory.GetFiles(sourceDir);
foreach(string fileName in fileEntries)
{
// do something with fileName
Console.WriteLine(fileName);
}
// Recurse into subdirectories of this directory.
string [] subdirEntries = Directory.GetDirectories(sourceDir);
foreach(string subdir in subdirEntries)
// Do not iterate through reparse points
if ((File.GetAttributes(subdir) &
FileAttributes.ReparsePoint) !=
FileAttributes.ReparsePoint)
ProcessDir(subdir,recursionLvl+1);
}
}
get all the files
string[] filePaths = Directory.GetFiles(#"c:\yourfolder\");
and iterate through it
use Directory.GetFiles()
foreach(var file in (myDir.GetFiles("*.jpg")
{
if(file.Name == "dog.jpg") return true;
}
var files = System.IO.Directory.GetFiles("directory", "*.jpg");
foreach (var item in files)
{
if (System.IO.Path.GetFileName(item) == "dog.jpg")
{
// File found.
}
}
DirectoryInfo di = new DirectoryInfo("c:\\Images");
var files = di.GetFiles("*.jpg");
foreach (var fileInfo in files)
{
if (fileInfo.Name == "dog.jpg")
return true;
}
return false;

Categories